package net.dgg.zz.production.inProcess.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.dgg.framework.tac.redis.utils.DggRedisUtils;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.entity.uc.CustomerDTO;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.OrfApiService;
import net.dgg.iboss.base.service.ScGeneralService;
import net.dgg.iboss.base.service.UcApiService;
import net.dgg.iboss.base.util.CustomerNumberEncryptionUtil;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.iboss.base.util.http.HttpUtility;
import net.dgg.iboss.base.util.http.ResultObj;
import net.dgg.tmd.foundation.platform.treebook.entity.TreeBook;
import net.dgg.tmd.foundation.platform.treebook.service.TreeBookService;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.datapermission.entity.DataAuthDTO;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserDTO;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.api.credential.entity.CertificateProductConfiguration;
import net.dgg.zz.api.credential.service.CertificateProductConfigurationService;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ApiUrlConstant;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.constant.ScNoteType;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.dao.ProductDao;
import net.dgg.zz.common.dto.TimeoutPunishDto;
import net.dgg.zz.common.entity.CustomerRecord;
import net.dgg.zz.common.entity.Node;
import net.dgg.zz.common.entity.Product;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.service.FlowService;
import net.dgg.zz.common.service.NodeTimeOutPunishService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.*;
import net.dgg.zz.credential.baseCredential.dao.BaseCredentialDao;
import net.dgg.zz.credential.baseCredential.entity.BaseCredential;
import net.dgg.zz.credential.baseCredential.entity.CredentialInfo;
import net.dgg.zz.credential.baseCredential.service.BaseCredentialService;
import net.dgg.zz.credential.baseCredential.service.CredentialInfoService;
import net.dgg.zz.credential.capitalPoolCount.service.CapitalPoolCountService;
import net.dgg.zz.credential.certificateMatching.entity.CertificateMatchingEntity;
import net.dgg.zz.credential.certificateMatching.service.CertificateMatchingService;
import net.dgg.zz.credential.certificateProduct.dao.CertificateProductDao;
import net.dgg.zz.credential.certificateProduct.entity.CertificateProduct;
import net.dgg.zz.credential.certificateProduct.service.CertificateProductService;
import net.dgg.zz.credential.certificateSpecialty.dao.CertificateSpecialtyDao;
import net.dgg.zz.credential.externalFunction.dao.ProductReservationDao;
import net.dgg.zz.credential.externalFunction.entity.ProductReservation;
import net.dgg.zz.credential.generalCredential.dao.GeneralCertificateDao;
import net.dgg.zz.credential.generalCredential.entity.GeneralCertificate;
import net.dgg.zz.credential.generalCredential.service.GeneralCredentialService;
import net.dgg.zz.credential.qualification.dao.QualificationDao;
import net.dgg.zz.credential.qualification.entity.Qualification;
import net.dgg.zz.credential.qualificationTransfer.dao.QualificationTransferDao;
import net.dgg.zz.credential.qualificationTransfer.entity.QualificationTransfer;
import net.dgg.zz.credential.storageCapacity.dao.StorageCapacityDao;
import net.dgg.zz.credential.storageCapacity.entity.StorageCapacity;
import net.dgg.zz.credential.storageCapacity.service.StorageCapacityService;
import net.dgg.zz.credential.warningConfigure.service.SystemConfigureService;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.entity.ProductTimeStatus;
import net.dgg.zz.production.entity.UnderOder;
import net.dgg.zz.production.excption.ProductOrderExcption;
import net.dgg.zz.production.inProcess.dao.*;
import net.dgg.zz.production.inProcess.entity.*;
import net.dgg.zz.production.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>@Title 办理中Service</p>
 * <p>@Description 办理中Service</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author maoquanyi</p>
 * <p>@date 2018年08月13日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@Service
public class ZzInProcessService extends BaseService {

    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    private UcApiService ucApiService;
    @Autowired
    private CertificateProductConfigurationService certificateProductConfigurationService;

    //新的引入
    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private AssistantDao assistantDao;
    @Autowired
    private ProductNodeDao productNodeDao;
    @Autowired
    private FilesRecordDao filesRecordDao;
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;
    @Autowired
    private ProductNodeOperatingDao productNodeOperatingDao;
    @Autowired
    private ProductDataDao productDataDao;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private ProductDao productDao;
    @Resource
    private DesUtil desUtil;
    @Resource
    private TranslateUtil translateUtil;
    @Autowired
    private CmsService cmsService;
    @Resource
    private GeneralCredentialService generalCredentialService;
    @Resource
    private BaseCredentialService baseCredentialService;
    @Resource
    private StorageCapacityDao storageCapacityDao;
    @Resource
    private CertificateSpecialtyDao certificateSpecialtyDao;
    @Resource
    private StorageCapacityService storageCapacityService;
    @Resource
    private BaseCredentialDao baseCredentialDao;
    @Resource
    private CertificateProductService certificateProductService;//证书生产中间表操作
    @Resource
    private CertificateProductDao certificateProductDao;
    @Resource
    private ProductReservationDao productReservationDao;
    @Resource
    private CommonService commonService;
    @Autowired
    private GeneralCertificateDao generalCertificateDao;
    @Resource
    private SystemConfigureService systemConfigureService;
    @Resource
    private QualificationDao qualificationDao;
    @Resource
    private QualificationTransferDao qualificationTransferDao;
    @Resource
    private UserService usersService;
    @Autowired
    private UserService userService;
    @Resource
    private OrfApiService orfApiService;
    @Resource
    private CapitalPoolCountService capitalPoolCountService;
    @Autowired
    private ScGeneralService scGeneralService;
    @Autowired
    private FlowService flowService;
    @Autowired
    private NodeTimeOutPunishService nodeTimeOutPunishService;
    @Autowired
    private CredentialInfoService credentialInfoService;
    @Autowired
    private CertificateMatchingService certificateMatchingService;
    @Autowired
    private InitComponent initComponent;
    @Resource
    private TreeBookService treeBookService;
    @Autowired
    private UnderOrderDao underOrderDao;


    /**
     * <p>@Description 查办理中分页列表</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/14 0014 17:33 创建时间</p>
     * <p>@return</p>
     */
    @Transactional(readOnly = true)
    public List<Map> queryInProcessListPage(Map params) {
        DataAuthDTO dataAuthDTO = new DataAuthDTO();
        params.put("dataAuthDTO", dataAuthDTO);
        params.put("userAlias", "t");
        params.put("userColumn", "flow_user_id");
        params.put("deptAlias", "t");
        params.put("deptColumn", "flow_user_org_id");
        Integer count = productOrderDao.inProcessCount(params);
        params.put("count", count);
        if (count < 1) {
            return new ArrayList<>();
        }
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "desc");
            params.put("orderColumn", "t.create_time");
        }
        List<Map> listPage = productOrderDao.queryInProcessListPage(params);
        params.put("count", count);
        return listPage;
    }

    /**
     * <p>@Description 查办理中分页列表</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/14 0014 17:33 创建时间</p>
     * <p>@return</p>
     */
    @Transactional(readOnly = true)
    public List<Map> queryInProcessQgjListPage(Map params) {
        Integer count = productOrderDao.inProcessCount(params);
        params.put("count", count);
        if (count < 1) {
            return new ArrayList<>();
        }
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "desc");
            params.put("orderColumn", "t.create_time");
        }
        List<Map> listPage = productOrderDao.queryInProcessListPage(params);
        params.put("count", count);
        return listPage;
    }

    /**
     * 根据条件查询记录-导出
     *
     * @param params
     * @return
     */
    public List<WaitAuditOrderVo> queryInProcessList(Map params) throws Exception {
        List<WaitAuditOrderVo> voList = new LinkedList<>();
        List<Map> srList = productOrderDao.queryInProcessList(params);
        for (int i = 0; i < srList.size(); i++) {
            WaitAuditOrderVo vo = new WaitAuditOrderVo();
            vo.setSignOrgName(String.valueOf(srList.get(i).get("signOrgName") == null ? "" : srList.get(i).get("signOrgName")));
            vo.setScProductOrderNo(String.valueOf(srList.get(i).get("scProductOrderNo") == null ? "" : srList.get(i).get("scProductOrderNo")));
            vo.setOrderNo(String.valueOf(srList.get(i).get("orderNo") == null ? "" : srList.get(i).get("orderNo")));
            vo.setContractNo(String.valueOf(srList.get(i).get("contractNo") == null ? "" : srList.get(i).get("contractNo")));
            vo.setCustomerName(String.valueOf(srList.get(i).get("customerName") == null ? "" : srList.get(i).get("customerName")));
            vo.setBusinessProductName(String.valueOf(srList.get(i).get("businessProductName") == null ? "" : srList.get(i).get("businessProductName")));
            vo.setProductName(String.valueOf(srList.get(i).get("productName") == null ? "" : srList.get(i).get("productName")));
            vo.setUpdateTime(String.valueOf(srList.get(i).get("updateTime") == null ? "" : srList.get(i).get("updateTime")));
            vo.setSignTime(String.valueOf(srList.get(i).get("signTime") == null ? "" : srList.get(i).get("signTime")));
            vo.setSignUserName(String.valueOf(srList.get(i).get("signUserName") == null ? "" : srList.get(i).get("signUserName")));
            vo.setSignUserOrgName(String.valueOf(srList.get(i).get("signUserOrgName") == null ? "" : srList.get(i).get("signUserOrgName")));
            vo.setFlowUserName(String.valueOf(srList.get(i).get("flowUserName") == null ? "" : srList.get(i).get("flowUserName")));
            vo.setFlowUserOrgName(String.valueOf(srList.get(i).get("flowUserOrgName") == null ? "" : srList.get(i).get("flowUserOrgName")));
            vo.setProductUserName(String.valueOf(srList.get(i).get("productUserName") == null ? "" : srList.get(i).get("productUserName")));
            vo.setCompanyName(String.valueOf(srList.get(i).get("companyName") == null ? "" : srList.get(i).get("companyName")));
            voList.add(vo);
        }
        return voList;
    }
    /**
     * 根据条件查询记录-导出
     *
     * @param params
     * @return
     */
    public List<WaitAuditOrderWjVo> queryInProcessWjList(Map params) throws Exception {
        List<WaitAuditOrderWjVo> voList = new LinkedList<>();
        List<Map> srList = productOrderDao.queryInProcessList(params);
        for (int i = 0; i < srList.size(); i++) {
            WaitAuditOrderWjVo vo = new WaitAuditOrderWjVo();
            vo.setSignOrgName(String.valueOf(srList.get(i).get("signOrgName") == null ? "" : srList.get(i).get("signOrgName")));
            vo.setScProductOrderNo(String.valueOf(srList.get(i).get("scProductOrderNo") == null ? "" : srList.get(i).get("scProductOrderNo")));
            vo.setOrderNo(String.valueOf(srList.get(i).get("orderNo") == null ? "" : srList.get(i).get("orderNo")));
            vo.setContractNo(String.valueOf(srList.get(i).get("contractNo") == null ? "" : srList.get(i).get("contractNo")));
            vo.setCustomerName(String.valueOf(srList.get(i).get("customerName") == null ? "" : srList.get(i).get("customerName")));
            vo.setBusinessProductName(String.valueOf(srList.get(i).get("businessProductName") == null ? "" : srList.get(i).get("businessProductName")));
            vo.setProductName(String.valueOf(srList.get(i).get("productName") == null ? "" : srList.get(i).get("productName")));
            vo.setCompletedTime(String.valueOf(srList.get(i).get("completedTime") == null ? "" : srList.get(i).get("completedTime")));
            vo.setSignTime(String.valueOf(srList.get(i).get("signTime") == null ? "" : srList.get(i).get("signTime")));
            vo.setSignUserName(String.valueOf(srList.get(i).get("signUserName") == null ? "" : srList.get(i).get("signUserName")));
            vo.setSignUserOrgName(String.valueOf(srList.get(i).get("signUserOrgName") == null ? "" : srList.get(i).get("signUserOrgName")));
            vo.setFlowUserName(String.valueOf(srList.get(i).get("flowUserName") == null ? "" : srList.get(i).get("flowUserName")));
            vo.setFlowUserOrgName(String.valueOf(srList.get(i).get("flowUserOrgName") == null ? "" : srList.get(i).get("flowUserOrgName")));
            vo.setProductUserName(String.valueOf(srList.get(i).get("productUserName") == null ? "" : srList.get(i).get("productUserName")));
            vo.setCompanyName(String.valueOf(srList.get(i).get("companyName") == null ? "" : srList.get(i).get("companyName")));
            voList.add(vo);
        }
        return voList;
    }

    /**
     * <p>@Description 查工作台办理超期分页列表</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/14 0014 17:33 创建时间</p>
     * <p>@return</p>
     */
    @Transactional(readOnly = true)
    public List<Map> queryExceedListPage(Map params) {
        Integer count = productOrderDao.exceedCount(params);
        params.put("count", count);
        if (count < 1) {
            return new ArrayList<>();
        }
        List<Map> listPage = productOrderDao.queryExceedListPage(params);
        params.put("count", count);
        return listPage;
    }


    /**
     * <p>@Description 查询生产订单详情</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/20 0020 11:27 创建时间</p>
     * <p>@return</p>
     */
    public Map<String, Object> queryScBaseInfo(Map params) {
        ValidateUtils.isTrue(!StringUtils.isEmpty(params.get("id")), ProductOrderExcption.class, "生产订单ID为空!");
        Map<String, Object> resultMap = new HashMap<>();
        //查询数据详情基础信息
        Map baseInfo = productOrderDao.queryProductMap(params);
        if (StringUtils.isNotEmpty(baseInfo.get("fomatOrderEndTime"))) {
            try {
                String fomatOrderEndTime = DateUtil.stringDateFormat(baseInfo.get("fomatOrderEndTime").toString(), "yyyy年MM月dd日");
                baseInfo.put("fomatOrderEndTime", fomatOrderEndTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        baseInfo.put("oldStatus", baseInfo.get("status"));
        //需要翻译的列
        String[] columnInfo = {"status", "businessAreaCode","serviceArea"};
        List<Map> list = new ArrayList<>();
        list.add(baseInfo);
        list = translateUtil.translateList(columnInfo, list);
        String[] hideColum = {"customerPhone", "contactPhone"};
        list = desUtil.decryptListMap(hideColum, list);//将数据库的电话号码先解密一次
        CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
        baseInfo = list.get(0);
        resultMap.put("baseInfo", baseInfo);
        //查询节点更新信息
        Object nodeFlowId = baseInfo.get("nodeFlowId");
        Long scOrderId = Long.valueOf(baseInfo.get("id").toString());
        //查询下一个节点信息
        ProductTimeStatus productTimeStatus = productTimeStatusDao.selectByPrimaryKey(scOrderId);
        resultMap.put("nextNodeInfo",productTimeStatus);
        //查节点
        ProductOrder productOrder = this.getScProductOrderById(scOrderId);
        List<Map> nodelist = null;
        if(StringUtils.isEmpty(productOrder.getFlowContent())){
            //老流程
            nodelist = this.queryNodeListByProductOrderId(scOrderId,(Long) nodeFlowId);
            resultMap.put("nodelist", nodelist);
        }else {
            nodelist = productNodeOperatingDao.queryProductNodeOperatingByScId(scOrderId);
            resultMap.put("nodelist", nodelist);
        }

        if (!StringUtils.isEmpty(productOrder.getFlowContent())) {
            List<Node> nextNodeList = new ArrayList<>();
            try {
                List<String> nodeNameList =nodelist.stream().map(ls->ls.get("nodeName").toString()).collect(Collectors.toList());
                nodeNameList = nodeNameList.stream().filter(ls ->!"完结".equals(ls)).collect(Collectors.toList());
                nextNodeList = flowService.getAfterKeyNode(scOrderId,nodeNameList);
            } catch (Exception e){
                System.out.println("获取订单当前节点之后的关键节点异常");
                e.printStackTrace();
            }
            resultMap.put("nextlist", nextNodeList);
        }
        //通过当前产品去产品配置中查询是否需要查看证书配置
        if(productOrder.getIsMatching() == 1){
            List<Map> matchCertificates = new ArrayList<>();
            //查询所需证书
            Map map = new HashMap();
            map.put("orderId",productOrder.getOrderId());
            map.put("orderBusId",productOrder.getOrderBusId());
            List<UnderOder> underOderList = underOrderDao.selectUnderOrderList(map);
            for(UnderOder underOder : underOderList){
                Map matchCertificateMap = new HashMap();
                underOder.setCertificateSpecialty(underOder.getCertificateSpecialty().replaceAll("\"", ""));
                matchCertificateMap.put("underOrder", underOder);
                Map param = new HashMap();
                param.put("id",productOrder.getId());
                param.put("certificateTypeId",underOder.getCertificateTypeId());
                String certificateSpecialtyId = underOder.getCertificateSpecialtyId();
                List<String> ccc = new ArrayList<>();
                if(certificateSpecialtyId.contains("[")){
                    String[] ss = certificateSpecialtyId.substring(2, certificateSpecialtyId.length() -2).replace("\"","").replace(" ","").split(",");
                    for (String s:ss) {
                        ccc.add(s);
                    }
                } else {
                    ccc = Arrays.asList(certificateSpecialtyId.substring(1, certificateSpecialtyId.length() - 1));
                }
                param.put("certificateSpecialtyIds",ccc);
                List<GeneralCertificate> generalCertificates = baseCredentialDao.findCertificateByScOrderId(param);
                matchCertificateMap.put("theMatched",generalCertificates);
                if(generalCertificates.size() >= underOder.getCount()){
                    matchCertificateMap.put("toMatch","ppjs");
                }else{
                    //封装查询参数
                    Map findCertificateByScOrderIdMap = new HashMap();
                    findCertificateByScOrderIdMap.put("certificateType",underOder.getCertificateTypeId());
                    findCertificateByScOrderIdMap.put("certificateSpecialtysArray",ccc);
                    findCertificateByScOrderIdMap.put("certificateLevel",underOder.getCertificateLevel());
                    findCertificateByScOrderIdMap.put("isAll","3");
                    findCertificateByScOrderIdMap.put("scOrderId",productOrder.getId());
                    findCertificateByScOrderIdMap.put("socialSecurityAreaId",underOder.getSocialSecurityAreaId());
                    findCertificateByScOrderIdMap.put("scCondition",1);
                    List<GeneralCertificate> generalCertificateList = generalCredentialService.queryGertificateInfo2(findCertificateByScOrderIdMap);
                    String[] generalCertificateColum = {"personalPhone"};
                    generalCertificateList = desUtil.decryptList(generalCertificateColum, generalCertificateList);//将数据库的电话号码先解密一次
                    generalCertificateList = CustomerNumberEncryptionUtil.encryptionList(generalCertificateColum, generalCertificateList);
                    matchCertificateMap.put("toMatch",generalCertificateList);
                }
                matchCertificates.add(matchCertificateMap);
            }
            resultMap.put("matchCertificates",matchCertificates);
        }
        //查询当前订单产品信息
        Map productList = productDao.queryProductByProductOrderId(params.get("id") + "");
        resultMap.put("productList", productList);
        //获取证书和资质相关状态
        Map cerdentialStatus = this.queryProductOrderCerdentialStatus(scOrderId);
        resultMap.put("cerdentialStatus", cerdentialStatus);
        //查询相关生产订单   ?? 订单状态还没有加
        Map<String, Object> relateMap = new HashMap<>();
        Object orderId = baseInfo.get("orderId");
        relateMap.put("orderId", orderId.toString());
        List<Map> relatedOrderList = productOrderDao.queryRelationProductOrder(relateMap);
        //需要翻译的列
        String[] columnRelated = {"status","serviceArea"};
        relatedOrderList = translateUtil.translateList(columnRelated, relatedOrderList);
        resultMap.put("relatedOrderList", relatedOrderList);
        //查询退单生产操作记录
        Map<String, Object> abandonMap = new HashMap<>();
        int[] operateTypeArr = {19, 46, 47};
        abandonMap.put("operateTypeArr", operateTypeArr);
        abandonMap.put("workId", scOrderId);
        List<SystemRecord> abandonRecordList = systemRecordService.findByParamsWithPage(abandonMap);
        resultMap.put("abandonRecordList", abandonRecordList);
        //查询客户基础信息
        if (StringUtils.isNotEmpty(baseInfo.get("customerId"))) {
            String customerId = baseInfo.get("customerId") + "";
            CustomerDTO customerDTO = ucApiService.findCustomerById(Long.parseLong(customerId));
            if (customerDTO != null) {
                String[] dtoColumn = {"sex", "origin", "businessArea", "customerType"};
                customerDTO = translateUtil.translateObject(dtoColumn, customerDTO);
                String number = this.desUtil.decrypt(customerDTO.getNumber());//解密电话号码

                customerDTO.setNumber(number);
                String[] customerPhone = {"number"};
                customerDTO = CustomerNumberEncryptionUtil.encryptionObject(customerPhone, customerDTO);

                // 备注信息
                StringBuilder stringBuilder = new StringBuilder();
                customerDTO.setLastFollowContent(stringBuilder
                        .append(customerDTO.getLastFollowContent() == null ? "" : customerDTO.getLastFollowContent())
                        .append(" (")
                        .append(customerDTO.getLastFollowerName() == null ? "" : customerDTO.getLastFollowerName())
                        .append(" ")
                        .append(DateUtil.dateToString(customerDTO.getLastFollowTime()))
                        .append(")")
                        .toString());
            }
            resultMap.put("customerDTO", customerDTO);
        }
        return resultMap;
    }

    /**
     * <p>@Description 通过客户ID查电话</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/13 0013 14:44 创建时间</p>
     * <p>@return</p>
     */
    public String findPhoneByCustomerId(Long customerId) {
        CustomerDTO customerDTO = ucApiService.findCustomerById(customerId);
        if (customerDTO != null) {
            String[] dtoColumn = {"sex", "origin", "businessArea", "customerType"};
            customerDTO = translateUtil.translateObject(dtoColumn, customerDTO);
            String number = this.desUtil.decrypt(customerDTO.getNumber());//解密电话号码
            customerDTO.setNumber(number);
            return customerDTO.getNumber();
        }
        return "";
    }

    /**
     * <p>@Description 根据生产订单ID 获取他的证书和资质匹配相关状态</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/31 0031 15:40 创建时间</p>
     * <p>@return map里面 zsStatusName 为证书相关状态,zzStatusName为资质相关状态 </p>
     */
    public Map queryProductOrderCerdentialStatus(Long scOrderId) {

        //查匹配的证书和资质信息
        Map statusMap = new HashMap<String, Long>() {{
            put("scOrderId", scOrderId);
        }};
        List<Map> twoStatus = baseCredentialDao.queryStatusAllByMap(statusMap);
        //根据生产订单查相关预约
        Map reserMap = new HashMap<String, Object>() {{
            put("scProductId", scOrderId);
            put("status", CredentialConstant.PRODUCT_RESERVATION_STATUS_RESERVATION);
        }};//只能查新增预约
        List<Map> reserMapList = productReservationDao.queryListByScOrderIdWithPage(reserMap);
        String zsStatusName = "未预约";//生产订单证书相关
        String zzStatusName = "未预约";//生产订单资质相关
        if (reserMapList != null && !reserMapList.isEmpty()) {
            for (Map map : reserMapList) {
                //有证书预约
                if (CredentialConstant.GENERAL_CREDENTIAL.equals(map.get("generalType").toString())) {
                    zsStatusName = "已预约";
                }
                if (CredentialConstant.ZZ_CREDENTIAL.equals(map.get("generalType").toString())) {
                    zzStatusName = "已预约";
                }
            }
        }
        for (Map mapStatus : twoStatus) {
            String generalType = mapStatus.get("generalType").toString();
            List<String> certificateStatus = Arrays.asList(mapStatus.get("certificateStatus").toString().split(","));
            if (CredentialConstant.GENERAL_CREDENTIAL.equals(generalType)) {//证书的状态
                if (certificateStatus.contains(CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE)) {
                    zsStatusName = "已使用";
                } else if (certificateStatus.contains(CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH)) {
                    zsStatusName = "已匹配";
                } else if (certificateStatus.contains(CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION)) {
                    zsStatusName = "已预定";
                }
            } else if (CredentialConstant.ZZ_CREDENTIAL.equals(generalType)) {//资质的状态
                if (certificateStatus.contains(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_FIVE)) {
                    zzStatusName = "已转让";
                } else if (certificateStatus.contains(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_THREE)
                        || certificateStatus.contains(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_FOUR)) {
                    zzStatusName = "已匹配";
                } else if (certificateStatus.contains(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_TWO)) {
                    zzStatusName = "已预定";
                }
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("zsStatusName", zsStatusName);
        resultMap.put("zzStatusName", zzStatusName);
        return resultMap;
    }


    /**
     * <p>@Description 更新节点前验证</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/14 0014 17:33 创建时间</p>
     * <p>@return</p>
     */
    public void validationUpdateNode(Long id) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(id, ProductOrderExcption.class, "生产订单ID不能为空！");
        ProductOrder productOrder = this.productOrderDao.selectByPrimaryKey(id);
        ValidateUtils.strNotEmpty(productOrder, ProductOrderExcption.class, "未查询到此生产主订单，请刷新列表！");
        List<Long> assis = new ArrayList<>();
        List<Assistant> assistantList = assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", productOrder.getId());
        }});
        //流程人员id
        assis.add(productOrder.getFlowUserId());
        //协单人员
        if (assistantList.size() >= 1) {
            for (Assistant assistant : assistantList) {
                assis.add(assistant.getAssistUserId());
            }
        }
        if (assistantList.size()==0) {
            ValidateUtils.isTrue((userEntity.getId().toString().equals(productOrder.getFlowUserId().toString()) || userEntity.getId().toString().equals(productOrder.getProductUserId().toString())), ProductOrderExcption.class, "不是流程人员或负责人，不能进行更新节点操作！");
        }
        //ValidateUtils.isTrue(assis.contains(userEntity.getId()), ProductOrderExcption.class, "您不是该订单的流程人员或协单人员，不能进行该操作！");
//        ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.SC_ORDER_IN_PROCESS), ProductOrderExcption.class, "此订单当前状态不是办理中不能操作该订单，请刷新列表！");
    }

    /**
     * <p>@Description 根据id查询生产订单</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/16 0016 15:25 创建时间</p>
     * <p>@return</p>
     */
    public ProductOrder getScProductOrderById(Long id) {
        ValidateUtils.strNotEmpty(id, ProductOrderExcption.class, "生产订单ID不能为空！");
        return productOrderDao.selectByPrimaryKey(id);
    }



    /**
     * <p>@Description 根据ids查询生产订单集合</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/16 0016 15:25 创建时间</p>
     * <p>@return</p>
     */
    public List<ProductOrder> getScProductOrderAllByIds(String ids) {
        JSONArray jsonArray = JSONArray.parseArray(ids);
        List<Long> idArray = jsonArray.toJavaList(Long.class);
        return productOrderDao.selectByPrimaryKeyAll(idArray);
    }


    /**
     * <p>@Description 根据流程节点id查询对应小业态所有节点</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/14 0014 17:33 创建时间</p>
     * <p>@return</p>
     */
    public List<ProductNode> queyNodeList(Long nodeFlowId) {
        ValidateUtils.strNotEmpty(nodeFlowId, ProductOrderExcption.class, "节点流程id不能为空!");
        List<ProductNode> nodelist = productNodeDao.query(new HashMap<String, Object>() {{
            put("processId", nodeFlowId);
            put("flag", 1);
        }});
        return nodelist;
    }

    /**
     * <p>@Description 查询一个生产订单流程对应的所有节点加上所有备注节点(详情历史生产备注使用)</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/23 0023 18:50 创建时间</p>
     * <p>@return</p>
     */
    public List<Map> queryNodeAndRemarksNode(Long scOrdId) {
        //查配好的备注产生的流程  ?? 问下这个怎么配置的
        //List<TreeBook> remarkslist = commonMangerExtService.queryTreeBookListByCode("SC_GENERAL_REMARKS", 1, null);
        //查生产订单对应流程的节点

        ProductOrder productOrder = this.getScProductOrderById(scOrdId);


        List<Map> remarksNodeAllList = new ArrayList<>();
        remarksNodeAllList.add(new HashMap<String, Object>() {{//先把备注加进去
            put("id", "20");
            put("name", "备注");
        }});
        remarksNodeAllList.add(new HashMap<String, Object>() {{//添加其他以便查询其他备注信息
            put("id", "21");
            put("name", "其他");
        }});
        Map<String, Object> remarksNodeMap;
        //for (TreeBook remarks : remarkslist) {
        //    remarksNodeMap = new HashMap<>();
        //    remarksNodeMap.put("code", remarks.getId());
        //    remarksNodeMap.put("name", remarks.getName());
        //    remarksNodeAllList.add(remarksNodeMap);
        //}
        if(StringUtils.isEmpty(productOrder.getFlowContent())){
            List<ProductNode> nodelist = this.queyNodeList(productOrder.getNodeFlowId());
            for (ProductNode node : nodelist) {
                remarksNodeMap = new HashMap<>();
                remarksNodeMap.put("id", node.getId());
                remarksNodeMap.put("name", node.getName());
                remarksNodeAllList.add(remarksNodeMap);
            }
        }else{
            List<Node> nodelist1 = new ArrayList<>();
            try {
                nodelist1 = flowService.getNode(scOrdId);
            } catch (Exception e){
                System.out.println("通过生产订单id获取流程节点异常");
                e.printStackTrace();
            }
            for (Node node : nodelist1) {
                remarksNodeMap = new HashMap<>();
                remarksNodeMap.put("id", node.getId());
                remarksNodeMap.put("name", node.getName());
                remarksNodeAllList.add(remarksNodeMap);
            }
        }


        return remarksNodeAllList;
    }

    /**
     * <p>@Description 根据生产订单ID,流程节点ID查详情使用的节点信息</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/20 0020 18:17 创建时间</p>
     * <p>@return</p>
     */
    public List<Map> queryNodeListByProductOrderId(Long productId, Long processId) {
        List<Map> maps = productNodeDao.queryNodeListByProductOrderId(new HashMap<String, Object>() {
            {
                put("productId", productId);
                put("processId", processId);
            }
        });
        return maps;
    }


    /**
     * <p>@Description 通过节点ID查节点</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/14 0014 17:33 创建时间</p>
     * <p>@return</p>
     */
    public List<ProductNode> queyNodeListById(Long nodeId) {
        List<ProductNode> nodelist = productNodeDao.query(new HashMap<String, Object>() {{
            put("id", nodeId);
            put("flag", 1);
        }});
        return nodelist;
    }


    /**
     * <p>@Description 查询生产订单关联的档案</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/14 0014 18:11 创建时间</p>
     * <p>@return</p>
     */
    public List<Map> queryFilesRecord(String orderId) {
        Map<String, Object> para = new HashMap<>();
        para.put("orderId", orderId);
        return filesRecordDao.queryMap(para);
    }

    /**
     * <p>@Description 详情页历史记录中的生产节点记录数据</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/23 0023 14:48 创建时间</p>
     * <p>@return</p>
     */
    public List<Map> queryProductOperatingList(Map params) {
        return productNodeOperatingDao.queryProductOperatingWithPage(params);
    }

    /**
     * <p>@Description 保存更新节点的信息</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/15 0015 11:23 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public Integer saveNodeUpdate(Map params, UserEntity userEntity) throws Exception {
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ProductOrder scProductOrder = this.productOrderDao.selectByPrimaryKey(Long.parseLong(params.get("scorderid").toString()));
        //查询是否是协单人员操作
        List<Assistant> assistantList = this.assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", scProductOrder.getId());
            put("assistUserId", userEntity.getId());
        }});
        //不是协单人员，判断是否是流程人员，也不是流程人员 就不呢更新节点
        if (assistantList.size()==0) {
            ValidateUtils.isTrue((userEntity.getId().toString().equals(scProductOrder.getFlowUserId().toString()) || userEntity.getId().toString().equals(scProductOrder.getProductUserId().toString())), ProductOrderExcption.class, "不是流程人员或负责人，不能进行更新节点操作！");
        }

        ValidateUtils.strNotEmpty(scProductOrder, ProductOrderExcption.class, "未获取到生产订单的信息！");
        ValidateUtils.isTrue((scProductOrder.getStatus().equals(ScProductConstant.SC_ORDER_IN_PROCESS) || scProductOrder.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_FPDJS) || scProductOrder.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_YJDJS) || scProductOrder.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_XDDJS) || scProductOrder.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_ZDDJS) || scProductOrder.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_TDDJS)), ProductOrderExcption.class, "该订单状态已不再办理中，不能进行更新节点操作！");
        ValidateUtils.strNotEmpty(scProductOrder.getAllotWay(), ProductOrderExcption.class, "未获取到生产订单的分配方式！");
        if(StringUtils.isEmpty(scProductOrder.getCurrentNodeId())){
            scProductOrder.setCurrentNodeId(scProductOrder.getLatestEndNodeId());
            scProductOrder.setCurrentNodeName(scProductOrder.getLatestEndNodeName());
        }
        int returnType = 0;
        //---------查询生产订单生产是否超期-----------
        List<ProductTimeStatus> productTimeStatusList = productTimeStatusDao.query(new HashMap<String, Object>() {{
            put("id", scProductOrder.getId());
        }});
        if(!StringUtils.isEmpty(scProductOrder.getFlowContent())){
            Node completeNode = flowService.queyNodeListByName(params.get("completeNodeName").toString(),Long.valueOf((String)params.get("scorderid")));
            //判断是否进行扣罚
            boolean state = isNodeTimeOutPunish(scProductOrder, productTimeStatusList.get(0));
            if (state) {
                Integer code = nodeTimeOutPunish(scProductOrder, completeNode, productTimeStatusList.get(0));
                if(0==code && "成都资质事业部".equals(scProductOrder.getProductOrgName())){
                    //发送扣罚消息
                    try {//不让影响其他功能
                        List<UserEntity> users = new ArrayList<>();
                        //扣罚人
                        UserEntity user = userService.findUserById(scProductOrder.getFlowUserId());
                        users.add(user);
                        //1.生产订单节点奖罚：您好，{生产订单编号}{客户名称}{订单产品}，xx节点超期产生扣罚，请查看确认。
                        String msg[] = new String[]{scProductOrder.getScProductOrderNo(),scProductOrder.getCustomerName(),scProductOrder.getProductName(),completeNode.getName()};
                        commonService.sendMsgByAsynchronous(users, msg, "ZZSC_NODE_PUNISH_ALERT");//匹配模板
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            scProductOrder.setPunishStatus(0);
        }
        ProductTimeStatus scProductTimeStatus = new ProductTimeStatus();
        String nextNodeId = "" != params.get("nextNodeId").toString() ? params.get("nextNodeId").toString(): params.get("completeNodeId").toString();
        Node node = new Node();
        if(StringUtils.isEmpty(scProductOrder.getFlowContent())){
            List<ProductNode> scProductNodes1 = productNodeDao.query(new HashMap<String, Object>() {{
                put("id",  nextNodeId);
            }});
            node.setId(scProductNodes1.get(0).getId());
            node.setName(scProductNodes1.get(0).getName());
            scProductTimeStatus = saveProductTimeStatusOld(scProductNodes1.get(0),scProductOrder);
        }else{
            Node nextNode = flowService.queyNodeListById( nextNodeId,Long.valueOf((String)params.get("scorderid")));
            node.setName(nextNode.getName());
            node.setId(nextNode.getId());
            scProductTimeStatus = saveProductTimeStatus(nextNode,scProductOrder);
        }

        //更新生产订单表
        scProductOrder.setCurrentNodeId((String) params.get("nextNodeId"));
        scProductOrder.setCurrentNodeName((String) params.get("nextNodeName"));
        scProductOrder.setLatestEndUserId(userEntity.getId());//最新节点更新人id
        scProductOrder.setLatestEndUserName(userEntity.getRealName().concat(userEntity.getLoginName())); //最新节点更新人
        scProductOrder.setLatestEndUserOrgId(userEntity.getOrgId());//最新更新人部门id
        if(!StringUtils.isEmpty(params.get("completeNodeId"))) {
            scProductOrder.setLatestEndNodeId((String) params.get("completeNodeId"));
            scProductOrder.setLatestEndNodeName((String) params.get("completeNodeName"));
            scProductOrder.setLatestEndNodeTime(new Date());
        }
        scProductOrder.setLatestEndNodeStatus(Integer.valueOf((String) params.get("isPass")));
        if(!scProductOrder.getStatus().equals(ScProductConstant.SC_ORDER_IN_PROCESS)){
            scProductOrder.setStatus(ScProductConstant.SC_ORDER_IN_PROCESS);
        }
        if("接单".equals(params.get("completeNodeName"))){
            if(StringUtils.isEmpty(scProductOrder.getReceiveTime())){
                scProductOrder.setReceiveTime(new Date());
            }
            if(StringUtils.isEmpty(scProductOrder.getReceiveOrderDate())){
                scProductOrder.setReceiveOrderDate(new Date());
            }
            if(StringUtils.isEmpty(scProductOrder.getReceiverId())){
                scProductOrder.setReceiverId(userEntity.getId());
                scProductOrder.setReceiverName(userEntity.getRealName().concat(userEntity.getLoginName()));
                Map org = commonMangerExtService.findOrg(userEntity.getOrgId());
                if (null != org) {
                    scProductOrder.setReceiverOrgId(Long.parseLong(org.get("id").toString()));
                    scProductOrder.setReceiverOrgName(org.get("name").toString());
                }
            }
        }
        //保存更新节点数据
        List<ProductNode> scProductNodes = new ArrayList<>();
        ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
        if(!StringUtils.isEmpty(scProductOrder.getFlowContent())) {
            Node completeNode = flowService.queyNodeListByName(params.get("completeNodeName").toString(), Long.valueOf((String) params.get("scorderid")));
            scProductNodeOperating = saveProductNodeOperating(scProductOrder, params, productTimeStatusList.get(0), userEntity, completeNode);
        }else{
            if(!StringUtils.isEmpty(params.get("completeNodeId"))){
                scProductNodes = productNodeDao.query(new HashMap<String, Object>() {{
                    put("id", params.get("completeNodeId"));
                }});
            }
            if(scProductNodes.size()>0) {
                if(!StringUtils.isEmpty(params.get("completeNodeId"))) {
                    scProductNodeOperating = saveProductNodeOperatingOld(scProductOrder, params, productTimeStatusList.get(0), userEntity, scProductNodes.get(0));
                }
            }
        }
        TreeBook treeBook = treeBookService.getTreeBookByCode("ZZSC_QGJ_EXCLUDE_PRODUCT");
        if(!StringUtils.isEmpty(params.get("nextNodeId"))) {
            if ("完结".equals(params.get("nextNodeName")) || "强制完结".equals(params.get("nextNodeName"))){
                if(treeBook.getExt1().equals(scProductOrder.getBusinessProductCode())){
                    getScProductConstant(scProductOrder, scProductTimeStatus);
                    Map organizationEntity = commonMangerExtService.findOrg(userEntity.getOrgId());
                    ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未获取到当前生产订单流程人员部门信息！");
                    Integer  timeType= scProductTimeStatus.getNodeProcessTimeType() == null ? scProductNodes.get(0).getIsNaturalorWorkday():Integer.valueOf(scProductTimeStatus.getNodeProcessTimeType());
                    Integer  processTime= scProductTimeStatus.getNodeProcessTime() == null ? scProductNodes.get(0).getHandleDate()/24 :scProductTimeStatus.getNodeProcessTime();
                    ProductNodeOperating operating = new ProductNodeOperating();
                    operating.setId(DggKeyWorker.nextId());
                    operating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
                    operating.setScProductOrderId(scProductOrder.getId());
                    operating.setScProductOrderNo(scProductOrder.getScProductOrderNo());
                    operating.setFlowOrgId(Long.valueOf(organizationEntity.get("id").toString()));
                    operating.setFlowOrgName(organizationEntity.get("name").toString());
                    operating.setFlowUserId(userEntity.getId());
                    operating.setFlowUserName(userEntity.getRealName().concat(userEntity.getLoginName()));
                    operating.setOrderStatus(scProductOrder.getStatus());
                    operating.setNodeId(scProductOrder.getCurrentNodeId());
                    operating.setNodeName(scProductOrder.getCurrentNodeName());
                    operating.setNodeProcessTimeType(timeType.toString()); //节点办理类型
                    operating.setNodeOpetateTime(new Date());
                    //scProductNodeOperating.setIsExtract(node.getIsExtract());
                    UserEntity currentUser = sessionManager.getCurrentUser();
                    Map curOrg = commonMangerExtService.findOrg(currentUser.getOrgId());
                    operating.setCreaterOrgName(curOrg.get("name").toString());
                    operating.setRemark("完结");
                    operating.setStatus(1);
                    //获取当前节点的配置的计算出的超期时间
                    Date currentDate = null;
                    if(null == scProductTimeStatus.getNodeEndTime()) {
                        currentDate = commonService.getDateFromStartByType(scProductOrder.getLatestEndNodeTime(),
                                processTime, scProductTimeStatus.getNodeSuspendMillisecond() == null ? 0 : scProductTimeStatus.getNodeSuspendMillisecond(),
                                timeType);
                    }else{
                        currentDate=scProductTimeStatus.getNodeEndTime();
                    }
                    //判断当前节点是否超期
                    if (currentDate.getTime() >= System.currentTimeMillis()) {
                        operating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点超期状态
                    } else {
                        operating.setNodeTimeStatus(ScProductConstant.TIME_OUT); //节点超期状态
                        String date = DateUtils.transTime(currentDate, new Date());
                        operating.setNodeOverdueTime(date); //节点超期时间
                    }
                    operating.setNodeProcessTime(scProductTimeStatus.getNodeProcessTime());
                    operating.setNodeStartTime(scProductTimeStatus.getNodeStartTime());
                    operating.setNodeEndTime(scProductTimeStatus.getNodeEndTime());
                    //保存更新节点数据
                    this.saveOpt(operating, userEntity);
                    this.updateOpt(operating, userEntity);
                    productNodeOperatingDao.insert(operating);
                }
            }
        }
        Object flowUserId = params.get("flowUserId");
        //未选择为当前操作者
        if (StringUtils.isEmpty(flowUserId)) {
            scProductOrder.setFlowUserId(userEntity.getId());
            scProductOrder.setFlowUserName(userEntity.getRealName().concat(userEntity.getLoginName()));
            Map org = commonMangerExtService.findOrg(userEntity.getOrgId());
            if (null != org) {
                scProductOrder.setFlowUserOrgId(Long.parseLong(org.get("id").toString()));
                scProductOrder.setFlowUserOrgName(org.get("name").toString());
            }
            //选择了下一更新人
        } else {
            Map flowUser = commonMangerExtService.searchUserById(Long.valueOf(flowUserId.toString()));
            Map org = commonMangerExtService.findOrg(Long.parseLong(flowUser.get("orgId").toString()));
            scProductOrder.setFlowUserId(Long.parseLong(flowUser.get("id").toString()));
            scProductOrder.setFlowUserName(flowUser.get("realName").toString().concat(flowUser.get("loginName").toString()));
            if (null != org) {
                scProductOrder.setFlowUserOrgId(Long.parseLong(org.get("id").toString()));
                scProductOrder.setFlowUserOrgName(org.get("name").toString());
            }
        }
        scProductOrder.setFlowType((String) params.get("flowType"));

        //----保存更新节点信息-----

        returnType = saveNodeUpdateNew(scProductOrder, params, userEntity, scProductTimeStatus, scProductNodeOperating);
        if (("完结".equals(params.get("nextNodeName")) || "强制完结".equals(params.get("nextNodeName"))) && !treeBook.getExt1().equals(scProductOrder.getBusinessProductCode())){
            //插入操作记录
            SystemRecord record = new SystemRecord();
            record.setId(DggKeyWorker.nextId());//id
            record.setSource("4");
            record.setWorkTableName("zzsc_product_order");
            record.setWorkId(scProductOrder.getId());
            record.setWorkNo(scProductOrder.getScProductOrderNo());
            record.setOperaterId(userEntity.getId());
            record.setOperateType("66");
            record.setRemarks("提交完结审核");
            systemRecordService.apiSave(record, userEntity);
        }
        //发送企管家消息
        String conent="您好，您的客户"+scProductOrder.getCustomerName()+"订单"+scProductOrder.getOrderNo()+"办理的"
                +scProductOrder.getScProductOrderNo()+"业务,"+params.get("completeNodeName")+"节点已更新,请及时查看沟通";
        commonService.sendQgjMessage(scProductOrder.getOrderId(),scProductOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),
                    userEntity.getLoginName(),conent);

        //scProductOrder.setLatestEndNodeTime(new Date()); //最新完成节点时间;
        try {
            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(scProductOrder, node,  userEntity);
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(scProductOrder.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(scProductOrder.getId());
            customerRecord.setTableNo(scProductOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE9);
            customerRecord.setCreaterId(userEntity.getId());
            if (StringUtils.isNotEmpty(params.get("remark"))){
                customerRecord.setContent(params.get("remark").toString());
            }
            MQMessageSendUtil.ucMessageSend(customerRecord);
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnType;
    }
    /**
     * <p>@Description 保存更新节点信息</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/15 0015 11:23 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public Integer saveNodeUpdateZz(ProductOrder scProductOrder, Map map, UserEntity userEntity, ProductTimeStatus scProductTimeStatus, ProductNode scProductNode) throws Exception {
        List<ProductData> productDataList = productDataDao.query(new HashMap<String, Object>() {{
            put("scProductId", scProductOrder.getId());
        }});
        int returnType = 0;
        if (productDataList != null && !productDataList.isEmpty()) {
            ProductData productData = productDataList.get(0);
            productData.setScProductId(scProductOrder.getId());
            productData.setScProductNo(scProductOrder.getScProductOrderNo());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //渠道
            if (null != map.get("channelName") && !"".equals(map.get("channelName"))) {
                productData.setChannelName(map.get("channelName").toString());
            }
            //资料交接数
            if (null != map.get("dataTransferNum") && !"".equals(map.get("dataTransferNum"))) {
                productData.setDataTransferNum(map.get("dataTransferNum").toString());
            }
            //网上审批时间
            if (null != map.get("netApprovalTime") && !"".equals(map.get("netApprovalTime"))) {
                productData.setNetApprovalTime(sdf.parse(map.get("netApprovalTime").toString()));
            }
            //评审时间
            if (null != map.get("reviewTime") && !"".equals(map.get("reviewTime"))) {
                productData.setReviewTime(sdf.parse(map.get("reviewTime").toString()));
            }
            //评审结果
            if (null != map.get("reviewResult") && !"".equals(map.get("reviewResult"))) {
                productData.setReviewResult(map.get("reviewResult").toString());
            }
            //公示时间
            if (null != map.get("publicityTime") && !"".equals(map.get("publicityTime"))) {
                productData.setPublicityTime(sdf.parse(map.get("publicityTime").toString()));
            }
            //报名时间
            if (null != map.get("signupTime") && !"".equals(map.get("signupTime"))) {
                productData.setSignupTime(sdf.parse(map.get("signupTime").toString()));
            }
            //换证时间
            if (null != map.get("replacementTime") && !"".equals(map.get("replacementTime"))) {
                productData.setReplacementTime(sdf.parse(map.get("replacementTime").toString()));
            }
            //打证时间
            if (null != map.get("playingcardsTime") && !"".equals(map.get("playingcardsTime"))) {
                productData.setPlayingcardsTime(sdf.parse(map.get("playingcardsTime").toString()));
            }
            //领证时间
            if (null != map.get("licensingTime") && !"".equals(map.get("licensingTime"))) {
                productData.setLicensingTime(sdf.parse(map.get("licensingTime").toString()));
            }
            //渠道返点
            if (null != map.get("channelRebates") && !"".equals(map.get("channelRebates"))) {
                productData.setChannelRebates(new BigDecimal(map.get("channelRebates").toString()));
            }
            //对外返点
            if (null != map.get("foreignRebates") && !"".equals(map.get("foreignRebates"))) {
                productData.setForeignRebates(new BigDecimal(map.get("foreignRebates").toString()));
            }
            //公示号
            if (null != map.get("publicityNum") && !"".equals(map.get("publicityNum"))) {
                productData.setPublicityNum(map.get("publicityNum").toString());
            }
            //公告时间
            if (null != map.get("noticeTime") && !"".equals(map.get("noticeTime"))) {
                productData.setNoticeTime(sdf.parse(map.get("noticeTime").toString()));
            }
            //公告号
            if (null != map.get("noticeNum") && !"".equals(map.get("noticeNum"))) {
                productData.setNoticeNum(map.get("noticeNum").toString());
            }
            //公告时间
            if (null != map.get("channelHisTime") && !"".equals(map.get("channelHisTime"))) {
                productData.setChannelHisTime(sdf.parse(map.get("channelHisTime").toString()));
            }
            //资质公司
            if (null != map.get("company") && !"".equals(map.get("company"))) {
                productData.setCompany(map.get("company").toString());
            }
            //招标文件
            if (null != map.get("biddingDocuments") && !"".equals(map.get("biddingDocuments"))) {
                productData.setBiddingDocuments(map.get("biddingDocuments").toString());
            }
            //招标清单
            if (null != map.get("biddingList") && !"".equals(map.get("biddingList"))) {
                productData.setBiddingList(map.get("biddingList").toString());
            }
            //标书数量
            if (null != map.get("bidingNum") && !"".equals(map.get("bidingNum"))) {
                productData.setBidingNum(map.get("bidingNum").toString());
            }
            //交标书时间
            if (null != map.get("handoveBidingTime") && !"".equals(map.get("handoveBidingTime"))) {
                productData.setHandoveBidingTime(sdf.parse(map.get("handoveBidingTime").toString()));
            }
            //公示文件
            if (null != map.get("publicityFile") && !"".equals(map.get("publicityFile"))) {
                productData.setPublicityFile(map.get("publicityFile").toString());
            }
            //审批通告时间
            if (null != map.get("approvalNoticeTime") && !"".equals(map.get("approvalNoticeTime"))) {
                productData.setApprovalNoticeTime(sdf.parse(map.get("approvalNoticeTime").toString()));
            }
            if (StringUtils.isNotEmpty(map.get("remark"))) {
                scProductOrder.setRemark(map.get("remark").toString());
                scProductOrder.setLastRemark(map.get("remark").toString());
                scProductOrder.setLastRemarkTime(new Date());
            }
            //保存操作记录
            SystemRecord systemRecord = new SystemRecord();
            systemRecord.setWorkId(productData.getId());
            systemRecord.setWorkTableName("zzsc_product_data");
            systemRecord.setRemarks("修改业态信息");
            systemRecord.setOperateType("2");//修改
            systemRecord.setSource("2");//来源生产
            systemRecordService.save(systemRecord);
            //-----------------保存更新节点记录      --------------------
            ProductNodeOperating scProductNodeOperating = saveScProductOperating(scProductOrder, scProductNode, map, scProductTimeStatus);
            scProductOrder.setLatestEndNodeTime(new Date());//设置最新更新节点时间
            //判断是否选择的完结
            if ("完结".equals(scProductOrder.getLatestEndNodeName()) || "强制完结".equals(scProductOrder.getLatestEndNodeName())) {
                //-------判断完结状态(正常，超期，强制)----------
                getScProductConstant(scProductOrder, scProductTimeStatus);
                scProductTimeStatus.setFlag(0); //完结后不执行
                returnType = 1;
                //更新订单超期表的节点超期状态
                String nodeTimeStatus = scProductNodeOperating.getNodeTimeStatus();
                scProductTimeStatus.setNodeTimeStatus(nodeTimeStatus);//这里做了修改,每次节点更新都更新订单的节点超期状态
            } else {
                String nodeTimeStatus = scProductNodeOperating.getNodeTimeStatus();
                scProductTimeStatus.setNodeTimeStatus(nodeTimeStatus);//这里做了修改,每次节点更新都更新订单的节点超期状态
            }

            //修改生产订单子表
            this.updateOpt(scProductOrder, userEntity);
            productOrderDao.updateByPrimaryKey(scProductOrder);
            //保存业态独有字段数据
            productDataDao.updateByPrimaryKey(productData);
            //保存更新节点数据
            this.saveOpt(scProductNodeOperating, userEntity);
            productNodeOperatingDao.insert(scProductNodeOperating);
            //更新超期表
            this.updateOpt(scProductTimeStatus, userEntity);
            productTimeStatusDao.updateByPrimaryKey(scProductTimeStatus);

            //////调用同步子订单接口  结项再处理
            //if (scProductOrder.getStatus().equals(ScProductConstant.SC_ORDER_OVER) || scProductOrder.getStatus().equals(ScProductConstant.SC_ORDER_OVER_OVERDUE)
            //        || scProductOrder.getStatus().equals(ScProductConstant.SC_ORDER_OVER_FORCE)) {
            //    this.updateOrderBusiness(scProductOrder, userEntity, "ORF_BDZT_1");
            //    //完结调用回访接口
            //    //this.saveRevisitCustomer(scProductOrder, userEntity, "BUS_STA_2_5");
            //}

            return returnType;
        }
        return null;
    }

    /**
     * <p>@Description 验证是否有权限详情编辑</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/17 0017 13:41 创建时间</p>
     * <p>@return</p>
     */
    public void checkIsFlowerOrAssister(Map map) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(map.get("scOrderId"), ProductOrderExcption.class, "未获取到生产订单ID,请刷新页面！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(Long.valueOf(map.get("scOrderId").toString()));
        List<Long> assis = new ArrayList<>();
        List<Assistant> assistantList = assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", productOrder.getId());
        }});
        //流程人员id
        assis.add(productOrder.getFlowUserId());
        //协单人员
        if (assistantList.size() >= 1) {
            for (Assistant assistant : assistantList) {
                assis.add(assistant.getAssistUserId());
            }
        }
        ValidateUtils.isTrue(assis.contains(userEntity.getId()), ProductOrderExcption.class, "您不是该订单的流程人员或协单人员，不能进行该操作！");
    }

    /**
     * <p>@Description 详情里面的保存</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/21 0021 17:11 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void saveProductOrderData(Map map) throws Exception {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(map.get("productOrderDataId"), ProductOrderExcption.class, "业态数据ID为空,请联系管理员!");
        Long productOrderDataId = Long.valueOf(map.get("productOrderDataId").toString());
        ValidateUtils.strNotEmpty(map.get("scOrderId"), ProductOrderExcption.class, "未获取到生产订单ID,请刷新页面！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(Long.valueOf(map.get("scOrderId").toString()));
        List<Long> assis = new ArrayList<>();
        List<Assistant> assistantList = assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", productOrder.getId());
        }});
        //流程人员id
        assis.add(productOrder.getFlowUserId());
        //协单人员
        if (assistantList.size() >= 1) {
            for (Assistant assistant : assistantList) {
                assis.add(assistant.getAssistUserId());
            }
        }
        ValidateUtils.isTrue(assis.contains(userEntity.getId()), ProductOrderExcption.class, "您不是该订单的流程人员或协单人员，不能进行该操作！");

        ProductData productData = productDataDao.selectByPrimaryKey(productOrderDataId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //渠道
        if (null != map.get("channelName") && !"".equals(map.get("channelName"))) {
            productData.setChannelName(map.get("channelName").toString());
        }else {
            productData.setChannelName(null);
        }
        //资料交接数
        if (null != map.get("dataTransferNum") && !"".equals(map.get("dataTransferNum"))) {
            productData.setDataTransferNum(map.get("dataTransferNum").toString());
        }else {
            productData.setDataTransferNum(null);
        }
        //网上审批时间
        if (null != map.get("netApprovalTime") && !"".equals(map.get("netApprovalTime"))) {
            productData.setNetApprovalTime(sdf.parse(map.get("netApprovalTime").toString()));
        }else {
            productData.setNetApprovalTime(null);
        }
        //评审时间
        if (null != map.get("reviewTime") && !"".equals(map.get("reviewTime"))) {
            productData.setReviewTime(sdf.parse(map.get("reviewTime").toString()));
        }else {
            productData.setReviewTime(null);
        }
        //评审结果
        if (null != map.get("reviewResult") && !"".equals(map.get("reviewResult"))) {
            productData.setReviewResult(map.get("reviewResult").toString());
        }else {
            productData.setReviewResult(null);
        }
        //公示时间
        if (null != map.get("publicityTime") && !"".equals(map.get("publicityTime"))) {
            productData.setPublicityTime(sdf.parse(map.get("publicityTime").toString()));
        }else {
            productData.setPublicityTime(null);
        }
        //报名时间
        if (null != map.get("signupTime") && !"".equals(map.get("signupTime"))) {
            productData.setSignupTime(sdf.parse(map.get("signupTime").toString()));
        }else {
            productData.setSignupTime(null);
        }
        //换证时间
        if (null != map.get("replacementTime") && !"".equals(map.get("replacementTime"))) {
            productData.setReplacementTime(sdf.parse(map.get("replacementTime").toString()));
        }else {
            productData.setReplacementTime(null);
        }
        //打证时间
        if (null != map.get("playingcardsTime") && !"".equals(map.get("playingcardsTime"))) {
            productData.setPlayingcardsTime(sdf.parse(map.get("playingcardsTime").toString()));
        }else {
            productData.setPlayingcardsTime(null);
        }
        //领证时间
        if (null != map.get("licensingTime") && !"".equals(map.get("licensingTime"))) {
            productData.setLicensingTime(sdf.parse(map.get("licensingTime").toString()));
        }else {
            productData.setLicensingTime(null);
        }
        //渠道返点
        if (null != map.get("channelRebates") && !"".equals(map.get("channelRebates"))) {
            productData.setChannelRebates(new BigDecimal(map.get("channelRebates").toString()));
        }else {
            productData.setChannelRebates(null);
        }
        //对外返点
        if (null != map.get("foreignRebates") && !"".equals(map.get("foreignRebates"))) {
            productData.setForeignRebates(new BigDecimal(map.get("foreignRebates").toString()));
        }else {
            productData.setForeignRebates(null);
        }
        //公示号
        if (null != map.get("publicityNum") && !"".equals(map.get("publicityNum"))) {
            productData.setPublicityNum(map.get("publicityNum").toString());
        }else {
            productData.setPublicityNum(null);
        }
        //公告时间
        if (null != map.get("noticeTime") && !"".equals(map.get("noticeTime"))) {
            productData.setNoticeTime(sdf.parse(map.get("noticeTime").toString()));
        }else {
            productData.setNoticeTime(null);
        }
        //公告号
        if (null != map.get("noticeNum") && !"".equals(map.get("noticeNum"))) {
            productData.setNoticeNum(map.get("noticeNum").toString());
        }else {
            productData.setNoticeNum(null);
        }
        //公告时间
        if (null != map.get("channelHisTime") && !"".equals(map.get("channelHisTime"))) {
            productData.setChannelHisTime(sdf.parse(map.get("channelHisTime").toString()));
        }else {
            productData.setChannelHisTime(null);
        }
        //资质公司
        if (null != map.get("company") && !"".equals(map.get("company"))) {
            productData.setCompany(map.get("company").toString());
        }else {
            productData.setCompany(null);
        }
        //招标文件
        if (null != map.get("biddingDocuments") && !"".equals(map.get("biddingDocuments"))) {
            productData.setBiddingDocuments(map.get("biddingDocuments").toString());
        }else {
            productData.setBiddingDocuments(null);
        }
        //招标清单
        if (null != map.get("biddingList") && !"".equals(map.get("biddingList"))) {
            productData.setBiddingList(map.get("biddingList").toString());
        }else {
            productData.setBiddingList(null);
        }
        //标书数量
        if (null != map.get("bidingNum") && !"".equals(map.get("bidingNum"))) {
            productData.setBidingNum(map.get("bidingNum").toString());
        }else {
            productData.setBidingNum(null);
        }
        //交标书时间
        if (null != map.get("handoveBidingTime") && !"".equals(map.get("handoveBidingTime"))) {
            productData.setHandoveBidingTime(sdf.parse(map.get("handoveBidingTime").toString()));
        }else {
            productData.setHandoveBidingTime(null);
        }
        //公示文件
        if (null != map.get("publicityFile") && !"".equals(map.get("publicityFile"))) {
            productData.setPublicityFile(map.get("publicityFile").toString());
        }else {
            productData.setPublicityFile(null);
        }
        //审批通告时间
        if (null != map.get("approvalNoticeTime") && !"".equals(map.get("approvalNoticeTime"))) {
            productData.setApprovalNoticeTime(sdf.parse(map.get("approvalNoticeTime").toString()));
        }else {
            productData.setApprovalNoticeTime(null);
        }
        //说明
        if (StringUtils.isNotEmpty(map.get("explains"))) {
            productData.setExplains(map.get("explains").toString());
        }else {
            productData.setExplains(null);
        }
        //企业名称
        if (null != map.get("companyName") && !"".equals(map.get("companyName"))) {
            productOrder.setCompanyName(map.get("companyName").toString());
        }else {
            productOrder.setCompanyName(null);
        }
        this.updateOpt(productData, userEntity);//更新人
        //保存操作记录
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setWorkId(productData.getId());
        systemRecord.setWorkTableName("zzsc_product_data");
        systemRecord.setRemarks("修改业态信息");
        systemRecord.setOperateType("2");//修改
        systemRecord.setSource("2");//来源生产
        systemRecordService.save(systemRecord);
        productDataDao.updateByPrimaryKey(productData);
        productOrderDao.updateByPrimaryKey(productOrder);
    }


    /**
     * <p>@Description 保存生产暂停</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/16 0016 15:23 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void suspendProOrder(Map params, UserEntity userEntity) throws ParseException {
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(params.get("id"), ProductOrderExcption.class, "生产订单ID为空！");
        ProductOrder scProOrder = this.productOrderDao.selectByPrimaryKey(Long.valueOf(params.get("id").toString()));
        ValidateUtils.strNotEmpty(scProOrder, ProductOrderExcption.class, "未查询到此生产订单，请刷新列表！");
//        ValidateUtils.isTrue(scProOrder.getFlowUserId().equals(userEntity.getId()), ProductOrderExcption.class, "您不是该订单的流程人员，没有权限操作！");
        ValidateUtils.isTrue(scProOrder.getStatus().equals(ScProductConstant.SC_ORDER_IN_PROCESS), ProductOrderExcption.class, "该订单状态已不在办理中，不能进行该操作！");
        ValidateUtils.strNotEmpty(params.get("remark"), ProductOrderExcption.class, "暂缓备注不能为空！");
        ValidateUtils.strNotEmpty(params.get("expectOpenTime"), ProductOrderExcption.class, "预计开启时间不能为空！");
        scProOrder.setRemark(params.get("remark").toString()); //备注
        scProOrder.setStatus(ScProductConstant.SC_ORDER_SUSPEND); //暂缓
        //暂停时间
        scProOrder.setSuspendTime(new Date());
        //最新备注时间
        scProOrder.setLastRemarkTime(new Date());
        scProOrder.setLastRemark(params.get("remark").toString());
        //查订单超期
        ProductTimeStatus scProductTimeStatus = productTimeStatusDao.selectByPrimaryKey(scProOrder.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        scProductTimeStatus.setExpectOpenDate(sdf.parse(params.get("expectOpenTime").toString())); //预计开启时间
        scProductTimeStatus.setExpectOpenTimeStatus(ScProductConstant.NORMAL); //正常
        //更新生产订单
        this.updateOpt(scProOrder, userEntity);
        productOrderDao.updateByPrimaryKey(scProOrder);

        //-------关闭订单超期表时间计算---------
        scProductTimeStatus.setFlag(0);
        scProductTimeStatus.setStartSuspendTime(new Date()); //暂停开始时间
        this.updateOpt(scProductTimeStatus, userEntity);
        productTimeStatusDao.updateByPrimaryKey(scProductTimeStatus);
        //保存操作记录
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setWorkId(scProOrder.getId());
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setRemarks("生产暂停(预计开启时间 " + params.get("expectOpenTime").toString() + "):" + params.get("remark").toString());
        systemRecord.setOperateType("27");//操作类型 : 生产暂停
        systemRecord.setSource("2");//来源生产
        systemRecordService.save(systemRecord);
        //通过MQ推送消息到UC
        CustomerRecord customerRecord = new CustomerRecord();
        customerRecord.setCustomerId(scProOrder.getCustomerId());
        customerRecord.setTableName("zzsc_product_order");
        customerRecord.setTableId(scProOrder.getId());
        customerRecord.setTableNo(scProOrder.getScProductOrderNo());
        customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE12);
        customerRecord.setCreaterId(userEntity.getId());
        if (StringUtils.isNotEmpty(params.get("remark"))){
            customerRecord.setContent(params.get("remark").toString());
        }
        MQMessageSendUtil.ucMessageSend(customerRecord);

        //提交之后，将订单信息同步到企大顺生产中心
        MQMessageSendUtil.qdsMessageSend(scProOrder, null,  userEntity);
        String msgConent="您好，您的客户"+scProOrder.getCustomerName()+"订单"+scProOrder.getOrderNo()+"办理的"+scProOrder.getScProductOrderNo()+"业务，订单已暂停,请及时确认处理";
        commonService.sendQgjMessage(scProOrder.getOrderId(),scProOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);

    }

    /**
     * <p>@Description 根据生产id查询协单人员</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/16 0016 16:41 创建时间</p>
     * <p>@return</p>
     */
    public List<Assistant> queyScAssistantList(Long id) {
        ValidateUtils.strNotEmpty(id, ProductOrderExcption.class, "生产订单id不能为空！");
        List<Assistant> scAssistantList = assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", id);
        }});
        return scAssistantList;
    }

    /**
     * <p>@Description 保存备注信息</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/16 0016 17:58 创建时间</p>
     * <p>@return</p>
     */
    public void saveOrderRemarks(Map map) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(map.get("scorderId"), ProductOrderExcption.class, "生产订单ID为空!");
        ValidateUtils.strNotEmpty(map.get("remark"), ProductOrderExcption.class, "备注不能为空!");
        Long scOrderId = Long.valueOf(map.get("scorderId").toString());
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(scOrderId);
        productOrder.setLastRemarkTime(new Date());//最新备注内容和时间
        productOrder.setLastRemark(map.get("remark").toString());
        this.updateOpt(productOrder,userEntity);
        productOrder.setLastUser(userEntity.getRealName()+" "+userEntity.getLoginName());
        productOrderDao.updateByPrimaryKey(productOrder);//修改生产订单
        //保存操作记录
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setWorkId(scOrderId);
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setRemarks(map.get("remark").toString());
        systemRecord.setOperateType("20");//操作类型 : 备注
        systemRecord.setSource("2");//来源生产
        systemRecordService.save(systemRecord);
        try {
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(productOrder.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(productOrder.getId());
            customerRecord.setTableNo(productOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE1);
            customerRecord.setCreaterId(userEntity.getId());
            if (StringUtils.isNotEmpty(map.get("remark"))){
                customerRecord.setContent(map.get("remark").toString());
            }
            MQMessageSendUtil.ucMessageSend(customerRecord);

            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(productOrder, null,  userEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
        String msgConent="您好，您的客户"+productOrder.getCustomerName()+"订单"+productOrder.getOrderNo()+"办理的"
                +productOrder.getScProductOrderNo()+"业务,添加一条备注信息,请及时查看";
        commonService.sendQgjMessage(productOrder.getOrderId(),productOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
    }

    /**
     * <p>@Description 保存添加协单人员</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/22 0022 9:20 创建时间</p>
     * <p>@return</p>
     */

    @Transactional
    public void updateAssist(Long productOrderId, String assistIds, UserEntity userEntity,Object type) {
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(productOrderId, ProductOrderExcption.class, "生产订单ID为空,请刷新页面重试！");
        ProductOrder scProductOrder = this.productOrderDao.selectByPrimaryKey(productOrderId);
        ValidateUtils.strNotEmpty(scProductOrder, ProductOrderExcption.class, "未查询到此生产订单，请刷新列表！");
        //分配的时候可以添加协单人员,所以取消流程人员限制
        //ValidateUtils.isTrue(scProductOrder.getFlowUserId().equals(userEntity.getId()),ProductOrderExcption.class,"您不是该订单的流程人员,没有权限操作！");
        if(StringUtils.isEmpty(type)){//如果是部门分单,就不验证
            ValidateUtils.isTrue(scProductOrder.getStatus().equals(ScProductConstant.SC_ORDER_IN_PROCESS)
                            || scProductOrder.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_XDDJS)
                            || scProductOrder.getStatus().equals(ScProductConstant.SC_ORDER_BACK_TO_ALLOT)
                            || scProductOrder.getStatus().equals(ScProductConstant.SC_ORDER_WAIT_ALLOT),
                    ProductOrderExcption.class, "该生产订单当前状态不能添加协单人员！");
        }
        //查询该生产订单相关的协单人员
        List<Assistant> scAssistants = this.assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", productOrderId);
        }});
        //保存协单人员变更记录
        saveScProductUserRecord(scAssistants, productOrderId, assistIds, scProductOrder,userEntity);
    }


    /**
     * <p>@Description 保存协单人员变更记录</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/22 0022 9:50 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void saveScProductUserRecord(List<Assistant> scAssistants, Long productOrderId, String assistIds,
                                        ProductOrder scProductOrder,UserEntity currentUser) {
        List<String> sysAs = new ArrayList<>();//修改前的协单人 ID
        List<String> newAs = new ArrayList<>();//现在传过来的协单人 ID
        List<String> delAs = new ArrayList<>(); // 标识为删除的
        List<String> addAs = new ArrayList<>(); // 标识为新增的
        //拿到修改前的协单人员
        if (scAssistants.size() > 0) {
            for (Assistant scAssistant : scAssistants) {
                sysAs.add(scAssistant.getAssistUserId().toString());
            }
        }
        if (null != assistIds && !"".equals(assistIds)) {
            String[] idsStrArray = assistIds.split(",");
            //判断协单人员变更还是新增
            newAs.addAll(Arrays.asList(idsStrArray));
            //新增的数据 addAs
            for (String s : newAs) {
                if (!sysAs.contains(s)) {
                    addAs.add(s);
                }
            }
        }
        //删除的数据 delAs
        for (String s : sysAs) {
            if (!newAs.contains(s)) {
                delAs.add(s);
            }
        }
        //删除多余的协单人员
        if (delAs.size() > 0) {
            for (String desId : delAs) {
                for (Assistant scAssistant : scAssistants) {
                    if (scAssistant.getAssistUserId().equals(Long.valueOf(desId))) {
                        assistantDao.deleteByPrimaryKey(scAssistant.getId());
                        break;
                    }
                }
            }
        }
        //保存新的数据
        if (addAs.size() > 0) {
            Assistant assistant = new Assistant();
            for (String addA : addAs) {
                Map user = commonMangerExtService.searchUserById(Long.valueOf(addA));
                Map org = commonMangerExtService.findOrg(Long.parseLong(user.get("orgId").toString()));
                assistant.setId(DggKeyWorker.nextId());
                assistant.setAssistUserId(Long.parseLong(user.get("id").toString()));
                assistant.setScProductOrderId(productOrderId);
                assistant.setAssistUserName(user.get("realName").toString() + user.get("loginName").toString());
                assistant.setLatestEndNodeId(scProductOrder.getLatestEndNodeId());
                if (null != org) {
                    assistant.setAssistUserOrgId(Long.parseLong(org.get("id").toString()));
                    assistant.setAssistUserOrgName(org.get("name").toString());
                }
                assistantDao.insert(assistant);
            }
        }
        //新增的记录
        UserEntity userEntity = new UserEntity();//协单人
        if (!addAs.isEmpty()) {
            for (String usid : addAs) {
                Map userMap = cmsService.findUser(Long.valueOf(usid));
                net.dgg.iboss.base.util.MapUtils.map2Bean(userEntity, userMap);
                //保存操作记录
                SystemRecord systemRecord = new SystemRecord();
                systemRecord.setWorkId(productOrderId);
                systemRecord.setWorkTableName("zzsc_assistant");
                systemRecord.setRemarks("新增协单人员");
                systemRecord.setOperateType("29");//操作类型 : 添加协单
                systemRecord.setSource("2");//来源生产
                systemRecordService.save(systemRecord, userEntity);
                //通过MQ推送消息到UC
                CustomerRecord customerRecord = new CustomerRecord();
                customerRecord.setCustomerId(scProductOrder.getCustomerId());
                customerRecord.setTableName("zzsc_product_order");
                customerRecord.setTableId(scProductOrder.getId());
                customerRecord.setTableNo(scProductOrder.getScProductOrderNo());
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE17);
                customerRecord.setCreaterId(currentUser.getId());
                customerRecord.setContent("添加协单人员");
                MQMessageSendUtil.ucMessageSend(customerRecord);

                //提交之后，将订单信息同步到企大顺生产中心
                MQMessageSendUtil.qdsMessageSend(scProductOrder, null,  userEntity);

                String msgConent="您好，您的客户"+scProductOrder.getCustomerName()+"订单"+scProductOrder.getOrderNo()
                        +"办理的"+scProductOrder.getScProductOrderNo()+"业务，已添加"+userEntity.getRealName()+"协单";
                commonService.sendQgjMessage(scProductOrder.getOrderId(),scProductOrder.getBusinessTypeCode(),currentUser.getId(),currentUser.getRealName(),currentUser.getLoginName(),msgConent);
            }
        }
        //删除的记录
        if (!delAs.isEmpty()) {
            for (String usid : delAs) {
                Map userMap = cmsService.findUser(Long.valueOf(usid));
                net.dgg.iboss.base.util.MapUtils.map2Bean(userEntity, userMap);
                //保存操作记录
                SystemRecord systemRecord = new SystemRecord();
                systemRecord.setWorkId(productOrderId);
                systemRecord.setWorkTableName("zzsc_assistant");
                systemRecord.setRemarks("删除协单人员");
                systemRecord.setOperateType("30");//操作类型 : 取消协单
                systemRecord.setSource("2");//来源生产
                systemRecordService.save(systemRecord, userEntity);
                //通过MQ推送消息到UC
                CustomerRecord customerRecord = new CustomerRecord();
                customerRecord.setCustomerId(scProductOrder.getCustomerId());
                customerRecord.setTableName("zzsc_product_order");
                customerRecord.setTableId(scProductOrder.getId());
                customerRecord.setTableNo(scProductOrder.getScProductOrderNo());
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE16);
                customerRecord.setCreaterId(currentUser.getId());
                customerRecord.setContent("取消协单人员");
                MQMessageSendUtil.ucMessageSend(customerRecord);
                //提交之后，将订单信息同步到企大顺生产中心
                MQMessageSendUtil.qdsMessageSend(scProductOrder, null,  currentUser);
                String msgConent="您好，您的客户"+scProductOrder.getCustomerName()+"订单"+scProductOrder.getOrderNo()
                        +"办理的"+scProductOrder.getScProductOrderNo()+"业务，已删除"+userEntity.getRealName()+"协单";
                commonService.sendQgjMessage(scProductOrder.getOrderId(),scProductOrder.getBusinessTypeCode(),currentUser.getId(),currentUser.getRealName(),currentUser.getLoginName(),msgConent);
            }
        }
    }


    /**
     * <p>@Description 保存申请退单</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/17 0017 10:01 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void abandonReasonOrder(Map params) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(params.get("id"), ProductOrderExcption.class, "生产订单ID为空！");
        ProductOrder scProOrder = this.productOrderDao.selectByPrimaryKey(Long.parseLong(params.get("id").toString()));
        ValidateUtils.strNotEmpty(scProOrder, ProductOrderExcption.class, "未查询到此生产订单，请刷新列表！");
        Map userAuditor = commonMangerExtService.searchUserById(Long.parseLong(params.get("auditorId").toString()));
        ValidateUtils.strNotEmpty(userAuditor, ProductOrderExcption.class, "未查询到选择的审核人，请从新选择审核人！");
        Map organizationEntity = commonMangerExtService.findOrg(Long.parseLong(userAuditor.get("orgId").toString()));
        ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未查询到选择的审核人，请从新选择审核人！");
        List<String> statusList = new ArrayList<>();
        statusList.add(ScProductConstant.SC_ORDER_CHARGEBACK_DSH); //退单待审核
        statusList.add(ScProductConstant.SC_ORDER_CHARGEBACK_TDBH);//退单驳回
        statusList.add(ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK);//已退单
        statusList.add(ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收
        statusList.add(ScProductConstant.SC_TO_RECEIVE_ZDDJS);//转单待接收
        statusList.add(ScProductConstant.SC_TO_RECEIVE_YJDJS);//移交待接收
        statusList.add(ScProductConstant.SC_TO_RECEIVE_TDDJS);//退回待接收
        statusList.add(ScProductConstant.SC_ORDER_SUSPEND);//生产暂停
        ValidateUtils.isTrue(!statusList.contains(scProOrder.getStatus()), ProductOrderExcption.class, "此订单当前状态不能操作退单，请刷新列表！");
        //调用IBOSS接口判断能否退单  打开注释即可
        try {
            orfApiService.isPossibleOrder(scProOrder.getOrderBusId());
        } catch (Exception e) {
            throw new ProductOrderExcption(e.getMessage());
        }
        SystemRecord systemRecord = new SystemRecord();
        if (StringUtils.isNotEmpty(params.get("remark"))) {
            scProOrder.setRemark(params.get("remark").toString());
            systemRecord.setRemarks(params.get("remark").toString());//备注记录
            //最新备注时间
            scProOrder.setLastRemarkTime(new Date());
            scProOrder.setLastUser(userEntity.getRealName() +" "+ userEntity.getLoginName());
            scProOrder.setLastRemark(params.get("remark").toString());
        }
        scProOrder.setBeforeStatus(scProOrder.getStatus());//退单之前的状态
        scProOrder.setAuditorId(Long.parseLong(userAuditor.get("id").toString()));
        scProOrder.setAuditorName(userAuditor.get("realName").toString().concat(userAuditor.get("loginName").toString()));
        scProOrder.setBeforeStatus(scProOrder.getStatus());//获取发起申请订单的状态
        scProOrder.setAbandonReasonTime(new Date()); //申请时间
        scProOrder.setAbandonReason(params.get("abandonReason").toString()); //申请类型
        scProOrder.setAbandonUserId(userEntity.getId()); //申请人ID
        scProOrder.setAbandonUser(userEntity.getRealName() + userEntity.getLoginName()); //申请人
        scProOrder.setStatus(ScProductConstant.SC_ORDER_CHARGEBACK_DSH); //退单待审核

        this.updateOpt(scProOrder, userEntity);
        //更新生产订单
        productOrderDao.updateByPrimaryKey(scProOrder);
        //记录
        systemRecord.setWorkId(scProOrder.getId());
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setOperateType("19");//操作类型 : 退单
        //查询退单原因
        String abandonReasonName = "无";
        List<TreeBook> list = commonMangerExtService.queryTreeBookListByCode(ScProductConstant.RETURENED_REASON, 1, null);
        if(list != null){
            Map<String, String> treebookMap = list.stream().collect(Collectors.toMap(t -> t.getCode(), t -> t.getName(), (v1, v2) -> v2));
            if(treebookMap.get(params.get("abandonReason").toString()) != null){
                abandonReasonName = treebookMap.get(params.get("abandonReason").toString());
            }
        }
        systemRecord.setRemarks("申请退单(理由 " + abandonReasonName + "):" + (params.get("remark") == null ? "无备注" : params.get("remark").toString()));
        systemRecord.setSource("2");//来源生产
        //保存操作记录
        systemRecordService.save(systemRecord);
        //推送消息
        List<UserEntity> users = new ArrayList<>();
        //签单商务
        UserEntity signUser = userService.findUserById(scProOrder.getSignUserId());
        if(signUser!=null){
            users.add(signUser);
        }
        //商务经理
        String[] codes = new String[]{"SWJL"};
        try {
            List<UserEntity> signUsers = userService.findUserByRoleCodesAndOrgs(codes, 0, scProOrder.getSignUserOrgId());
            users.addAll(signUsers);
        }catch (Exception e ){
            e.getMessage();
        }
        //后台经理
        String[] flowCodes = new String[]{"ZZSC_HTMANAGER"};
        if(scProOrder.getFlowUserOrgId()!=null){
            UserEntity FlowUser = userService.findUserById(scProOrder.getFlowUserId());
            if(signUser!=null){
                users.add(FlowUser);
            }
            List<UserEntity> flowUsers = userService.findUserByRoleCodesAndOrgs(flowCodes, 0, scProOrder.getFlowUserOrgId());
            users.addAll(flowUsers);
        }
        String[] msg = new String[]{scProOrder.getScProductOrderNo(),scProOrder.getOrderNo(),DateUtils.dateString(scProOrder.getAbandonReasonTime(),DateUtils.yyyy_MM_dd_HH_mm_ss)};
        try {
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(scProOrder.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(scProOrder.getId());
            customerRecord.setTableNo(scProOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE3);
            customerRecord.setCreaterId(userEntity.getId());
            if (StringUtils.isNotEmpty(params.get("remark"))){
            customerRecord.setContent(params.get("remark").toString());
            }
            MQMessageSendUtil.ucMessageSend(customerRecord);

            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(scProOrder, null,  userEntity);

            commonService.sendMsgByAsynchronous(users,msg,"ZZSC_SC_RETURN_ORDER");
            String msgConent="您好，您的客户"+scProOrder.getCustomerName()+"订单"+scProOrder.getOrderNo()+"办理的"
                    +scProOrder.getScProductOrderNo()+"业务,订单申请退单,请及时确认处理";
            commonService.sendQgjMessage(scProOrder.getOrderId(),scProOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
        }catch (Exception e){
            //不处理也不抛出,不成功就算了
        }

    }

    /**
     * <p>@Description 判断生产订单完结状态(正常，超期，强制)</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/15 0015 14:27 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public ProductOrder getScProductConstant(ProductOrder scProductOrder, ProductTimeStatus scProductTimeStatus) {
        if ("强制完结".equals(scProductOrder.getCurrentNodeName())) {
            scProductOrder.setStatus(ScProductConstant.SC_ORDER_OVER_FORCE); //强制完结
            scProductOrder.setCompletedTime(new Date());
        }
        //订单正常完结且没有超期的
        if ("完结".equals(scProductOrder.getCurrentNodeName()) && ScProductConstant.NORMAL.equals(scProductTimeStatus.getOrderTimeStatus())) {
            scProductOrder.setStatus(ScProductConstant.SC_ORDER_OVER);//正常完结
            scProductOrder.setCompletedTime(new Date());
        }//订单正常完结且已经超期的
        else if ("完结".equals(scProductOrder.getCurrentNodeName()) && ScProductConstant.TIME_OUT.equals(scProductTimeStatus.getOrderTimeStatus())) {
            scProductOrder.setStatus(ScProductConstant.SC_ORDER_OVER_OVERDUE); //超期完结
            scProductOrder.setCompletedTime(new Date());
        }
        return scProductOrder;
    }

    /**
     * <p>@Description 更新节点时的 保存节点记录信息</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/24 0024 8:40 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public ProductNodeOperating saveScProductOperating(ProductOrder scProductOrder, ProductNode scProductNode, Map map, ProductTimeStatus scProductTimeStatus) {
        Map flowUser = commonMangerExtService.searchUserById(scProductOrder.getFlowUserId());
        ValidateUtils.strNotEmpty(flowUser, ProductOrderExcption.class, "未获取到当前生产订单流程人员信息！");
        Map organizationEntity = commonMangerExtService.findOrg(Long.parseLong(flowUser.get("orgId").toString()));
        ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未获取到当前生产订单流程人员部门信息！");
        ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
        scProductNodeOperating.setId(DggKeyWorker.nextId());
        scProductNodeOperating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
        scProductNodeOperating.setScProductOrderId(scProductOrder.getId());
        scProductNodeOperating.setScProductOrderNo(scProductOrder.getScProductOrderNo());
        scProductNodeOperating.setFlowOrgId(Long.parseLong(organizationEntity.get("id").toString()));
        scProductNodeOperating.setFlowOrgName(organizationEntity.get("name").toString());
        scProductNodeOperating.setFlowUserId(scProductOrder.getFlowUserId());
        scProductNodeOperating.setFlowUserName(scProductOrder.getFlowUserName());
        scProductNodeOperating.setOrderStatus(scProductOrder.getStatus());
        scProductNodeOperating.setNodeId(scProductOrder.getLatestEndNodeId());
        scProductNodeOperating.setNodeName(scProductOrder.getLatestEndNodeName());
        scProductNodeOperating.setNodeProcessTimeType(scProductNode.getIsNaturalorWorkday().toString()); //节点办理类型
        scProductNodeOperating.setNodeOpetateTime(new Date());
        UserEntity currentUser = sessionManager.getCurrentUser();
        Map curOrg = commonMangerExtService.findOrg(currentUser.getOrgId());
        scProductNodeOperating.setCreaterOrgName(curOrg.get("name").toString());

        if (null != map.get("remark") && !"".equals(map.get("remark"))) {
            scProductNodeOperating.setRemark("更新节点:" + map.get("remark").toString());
        }
        //获取当前节点的配置的计算出的超期时间
        Date currentDate = commonService.getDateFromStartByType(scProductOrder.getLatestEndNodeTime(),
                scProductNode.getHandleDate(), scProductTimeStatus.getNodeSuspendMillisecond() == null ? 0 : scProductTimeStatus.getNodeSuspendMillisecond(),
                scProductNode.getIsNaturalorWorkday());
        //判断当前节点是否超期
        if (currentDate.getTime() >= System.currentTimeMillis()) {
            scProductNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点超期状态
        } else {
            scProductNodeOperating.setNodeTimeStatus(ScProductConstant.TIME_OUT); //节点超期状态
            String date = DateUtils.transTime(currentDate, new Date());
            scProductNodeOperating.setNodeOverdueTime(date); //节点超期时间
        }
        scProductNodeOperating.setNodeProcessTime(scProductTimeStatus.getNodeProcessTime());
        scProductNodeOperating.setNodeStartTime(scProductTimeStatus.getNodeStartTime());
        scProductNodeOperating.setNodeEndTime(scProductTimeStatus.getNodeEndTime());
        return scProductNodeOperating;
    }

    /**
     * <p>@Description 详情中的  根据节点的生产备注</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/24 0024 8:41 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void saveProductOperatingByDetail(Map params) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人信息,请重新登陆！");
        Map userOrg = commonMangerExtService.findOrg(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(userOrg, ProductOrderExcption.class, "未获取到登陆人的部门信息,请重新登陆！");
        ValidateUtils.strNotEmpty(params.get("remark"), ProductOrderExcption.class, "生产备注不能为空！");
        ValidateUtils.strNotEmpty(params.get("productOrderId"), ProductOrderExcption.class, "生产订单ID为空,请刷新页面重试！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(Long.valueOf(params.get("productOrderId").toString()));
        Map flowUser = commonMangerExtService.searchUserById(productOrder.getFlowUserId());
        ValidateUtils.isTrue(flowUser.size() != 0, ProductOrderExcption.class, "未获取到当前生产订单流程人员信息,不能备注！");
        Map organizationEntity = commonMangerExtService.findOrg(Long.parseLong(flowUser.get("orgId").toString()));
        ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未获取到当前生产订单流程人员部门信息！");
        ValidateUtils.strNotEmpty(params.get("nodeId"), ProductOrderExcption.class, "备注节点不能为空！");
        ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
        scProductNodeOperating.setId(DggKeyWorker.nextId());
        scProductNodeOperating.setRemarksType(2);   //(记录类型  1：节点更新，2：备注)
        scProductNodeOperating.setScProductOrderId(productOrder.getId());
        scProductNodeOperating.setScProductOrderNo(productOrder.getScProductOrderNo());
        scProductNodeOperating.setFlowOrgId(Long.parseLong(organizationEntity.get("id").toString()));
        scProductNodeOperating.setFlowOrgName(organizationEntity.get("name").toString());
        scProductNodeOperating.setFlowUserId(productOrder.getFlowUserId());
        scProductNodeOperating.setFlowUserName(productOrder.getFlowUserName());
        scProductNodeOperating.setOrderStatus(productOrder.getStatus());
        String nodeId = params.get("nodeId").toString();
        scProductNodeOperating.setNodeId(nodeId);
        scProductNodeOperating.setNodeName(params.get("nodeName").toString() + "备注");
        this.saveOpt(scProductNodeOperating, userEntity);
        scProductNodeOperating.setRemark(params.get("remark").toString());
        scProductNodeOperating.setCreaterOrgName(userOrg.get("name").toString());
        productNodeOperatingDao.insert(scProductNodeOperating);
        //更新最新备注时间
        productOrder.setLastRemarkTime(new Date());
        productOrder.setLastRemark(params.get("remark").toString());
        this.updateOpt(productOrder,userEntity);
        productOrderDao.updateByPrimaryKey(productOrder);//更新生产订单
        //通过MQ推送消息到UC
        CustomerRecord customerRecord = new CustomerRecord();
        customerRecord.setCustomerId(productOrder.getCustomerId());
        customerRecord.setTableName("zzsc_product_order");
        customerRecord.setTableId(productOrder.getId());
        customerRecord.setTableNo(productOrder.getScProductOrderNo());
        customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE26);
        customerRecord.setCreaterId(userEntity.getId());
        if (StringUtils.isNotEmpty(params.get("remark"))){
            customerRecord.setContent(params.get("remark").toString());
        }
        MQMessageSendUtil.ucMessageSend(customerRecord);

        //提交之后，将订单信息同步到企大顺生产中心
        MQMessageSendUtil.qdsMessageSend(productOrder, null,  userEntity);
    }

    /**
     * 同步备注
     *
     * @param scProductOrder
     * @param userEntity
     * @param opeType
     */
    public void syscScOrderRemarkToUc(ProductOrder scProductOrder, UserEntity userEntity, String opeType) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("customerId", scProductOrder.getCustomerId()); // 客户ID
            paramMap.put("tableId", scProductOrder.getId());
            paramMap.put("tableName", "sc_product_order");
            paramMap.put("tableNo", scProductOrder.getScProductOrderNo());
            paramMap.put("remarkType", opeType);
            paramMap.put("content", scProductOrder.getRemark());
            paramMap.put("createrId", userEntity.getId());

            int i = this.ucApiService.saveCustomerRecord(paramMap);
            Assert.isTrue(i == 0, "同步生产主订单的备注到客户系统失败！");
        } catch (Exception e) {
            e.printStackTrace();
            Assert.isTrue(false, "同步生产主订单的备注到客户系统时发生异常！");
        }
    }

    /**
     * <p>@Description 同步状态</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/5 0005 10:27 创建时间</p>
     * <p>@return</p>
     */
    public void updateOrderBusiness(ProductOrder scProductOrder, UserEntity userEntity, String status) {
        //同步修改子订单接口
        Map map = new HashMap<String, Object>() {{
            put("scProductOrderId", scProductOrder.getId());
        }};
        Product product = productDao.findProductByOrderId(map);
        orfApiService.updateOrderBusiness(scProductOrder.getOrderId(), product.getId().toString(), userEntity.getId(), status, null);
    }

    /**
     * <p>@Description 完结同步IBOSS主订单</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/25 0025 15:45 创建时间</p>
     * <p>@return</p>
     */
    public void updateOrderIboss(ProductOrder scProductOrder, UserEntity userEntity, String status) {
        //同步修改订单接口
        orfApiService.updateOrder(scProductOrder.getOrderId(), userEntity.getId(), status, null);
    }

    /**
     * 生产订单完结，新增回访
     *
     * @param scProductOrder
     * @param userEntity
     */
    public void saveRevisitCustomer(ProductOrder scProductOrder, UserEntity userEntity, String code) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("createrId", userEntity.getId());
            params.put("createrName", userEntity.getLoginName());
            params.put("customerId", scProductOrder.getCustomerId());
            params.put("businessId", scProductOrder.getBusinessId());
            params.put("businessNo", scProductOrder.getBusinessNo());
            params.put("businessStatus", code);
            params.put("signOrderTime", DateUtil.dateToString(scProductOrder.getOrderTime()));
            params.put("successOrderTime", DateUtil.dateToString(scProductOrder.getCompletedTime()));
            params.put("orderUserId", scProductOrder.getSignUserId());
            params.put("orderUserName", scProductOrder.getSignUserName());
            params.put("orderId", scProductOrder.getOrderId());
            params.put("orderNo", scProductOrder.getOrderNo());
            ucApiService.saveRevisitCustomer(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * <p>@Description 修改协单人员操作的节点</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/15 0015 14:22 创建时间</p>
     * <p>@return</p>
     */
    private void updateScAssistants(List<Assistant> scAssistants, Node node, UserEntity userEntity) {
        for (Assistant assistant : scAssistants) {
            assistant.setLatestEndNodeName(node.getName());
            assistant.setLatestEndNodeId(node.getName());
            assistant.setLatestEndNodeTime(new Date());
            updateOpt(assistant, userEntity);
            assistantDao.updateByPrimaryKey(assistant);
        }
    }

    /**
     * <p>@Description 移交保存</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/12 0012 11:31 创建时间</p>
     * <p>@return</p>
     */
    public void saveTurnOver(Map map) {
        ValidateUtils.strNotEmpty(map.get("idStr"), ProductOrderExcption.class, "生产订单ID不能为空!");
        ValidateUtils.strNotEmpty(map.get("assistId"), ProductOrderExcption.class, "负责人不能为空!");
        UserEntity userEntity = sessionManager.getCurrentUser();
        Long assistId = Long.valueOf(map.get("assistId").toString());
        UserEntity flower = userService.findUserById(assistId);
        Map flowOrg = commonMangerExtService.findOrg(flower.getOrgId());
        ValidateUtils.strNotEmpty(flowOrg, ProductOrderExcption.class, "未获取到负责人部门,请重新选择负责人!");
        String idStr = map.get("idStr").toString();
        Object remark = map.get("remark");
        String[] split = idStr.split(",");
        //操作记录
        SystemRecord systemRecord = new SystemRecord();
        for (String productId : split) {
            ProductOrder productOrder = productOrderDao.selectByPrimaryKey(Long.valueOf(productId));
            ValidateUtils.isTrue(!ScProductConstant.SC_TO_RECEIVE_XDDJS.equals(productOrder.getStatus()) &&
                    !ScProductConstant.SC_ORDER_BACK_TO_ALLOT.equals(productOrder.getStatus()), ProductOrderExcption.class, "待分配订单不能移交!");
            if (productOrder.getAllotWay() == null) {
                throw new ProductOrderExcption("订单编号:" + productOrder.getScProductOrderNo() + "为待分配订单退单,不能移交!");
            }
            //移交前的人
            if (productOrder.getFlowUserId() != null) {//流程人员
                productOrder.setWaitingReceiverId(productOrder.getFlowUserId());
                productOrder.setWaitingReceiverName(productOrder.getFlowUserName());
                productOrder.setWaitingReceiverOrgId(productOrder.getFlowUserOrgId());
                productOrder.setWaitingReceiverOrgName(productOrder.getFlowUserOrgName());
            } else if (productOrder.getProductUserId() != null) {//没有就拿生产负责人
                productOrder.setWaitingReceiverId(productOrder.getProductUserId());
                productOrder.setWaitingReceiverName(productOrder.getProductUserName());
                productOrder.setWaitingReceiverOrgId(productOrder.getProductUserOrgId());
                productOrder.setWaitingReceiverOrgName(productOrder.getProductUserOrgName());
            } else {//没有拿接收人
                productOrder.setWaitingReceiverId(productOrder.getReceiverId());
                productOrder.setWaitingReceiverName(productOrder.getReceiverName());
                productOrder.setWaitingReceiverOrgId(productOrder.getReceiverOrgId());
                productOrder.setWaitingReceiverOrgName(productOrder.getReceiverOrgName());
            }
            //接收人
            if (ScProductConstant.ALLOT_TO_FLOW_USER.equals(productOrder.getAllotWay())) {
                productOrder.setReceiverId(assistId);
                productOrder.setReceiverName(flower.getRealName() + flower.getLoginName());
                productOrder.setReceiverOrgId(flower.getOrgId());
                productOrder.setReceiverOrgName(flowOrg.get("name").toString());
            } else {//负责人
                productOrder.setReceiverId(assistId);
                productOrder.setReceiverName(flower.getRealName() + flower.getLoginName());
                productOrder.setReceiverOrgId(flower.getOrgId());
                productOrder.setReceiverOrgName(flowOrg.get("name").toString());
                productOrder.setProductUserId(assistId);
                productOrder.setProductUserName(flower.getRealName() + flower.getLoginName());
                productOrder.setProductUserOrgId(flower.getOrgId());
                productOrder.setProductUserOrgName(flowOrg.get("name").toString());
            }
            String status = productOrder.getStatus();
            //只有办理中和待接收的移交之后需要改变状态
            if (ScProductConstant.SC_TO_RECEIVE_FPDJS.equals(status) || ScProductConstant.SC_TO_RECEIVE_ZDDJS.equals(status)
                    || ScProductConstant.SC_TO_RECEIVE_YJDJS.equals(status) || ScProductConstant.SC_TO_RECEIVE_TDDJS.equals(status)
                    || ScProductConstant.SC_ORDER_IN_PROCESS.equals(status)) {
                productOrder.setStatus(ScProductConstant.SC_TO_RECEIVE_YJDJS);
            }
            productOrder.setFlowUserId(assistId);
            productOrder.setFlowUserName(flower.getRealName() + flower.getLoginName());
            productOrder.setFlowUserOrgId(flower.getOrgId());
            productOrder.setFlowUserOrgName(flowOrg.get("name").toString());
            //修改退单 相关
            if (ScProductConstant.SC_ORDER_CHARGEBACK_DSH.equals(status) || ScProductConstant.SC_ORDER_CHARGEBACK_TDBH.equals(status)
                    || ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK.equals(status)) {
                if (productOrder.getAbandonUserId() != null) {//修改退单申请人
                    productOrder.setAbandonUserId(assistId);
                    productOrder.setAbandonUser(flower.getRealName() + flower.getLoginName());
                }
            }
            productOrder.setOriginCode(ScProductConstant.ORDER_SOURCE_TRANSFER);//修改来源方式
            if (StringUtils.isNotEmpty(remark)) {
                productOrder.setRemark(remark.toString());
                //最新备注时间
                productOrder.setLastRemarkTime(new Date());
                productOrder.setLastRemark(remark.toString());
            }
            this.updateOpt(productOrder, sessionManager.getCurrentUser());
            productOrderDao.updateByPrimaryKey(productOrder);

            systemRecord.setWorkId(productOrder.getId());
            systemRecord.setWorkNo(productOrder.getScProductOrderNo());
            systemRecord.setWorkTableName("zzsc_product_order");
            systemRecord.setSource("2");//来源生产
            systemRecord.setOperateType("26");//操作类型 : 移交
            systemRecord.setRemarks("移交生产订单");
            systemRecordService.save(systemRecord, flower);//保存上被操作人
            //调用发送消息公共方法
            // 生产订单{0}已经于{1}移交给你，请及时确认处理！
            try {//不让影响其他功能,发送失败就算了
                //通过MQ推送消息到UC
                CustomerRecord customerRecord = new CustomerRecord();
                customerRecord.setCustomerId(productOrder.getCustomerId());
                customerRecord.setTableName("zzsc_product_order");
                customerRecord.setTableId(productOrder.getId());
                customerRecord.setTableNo(productOrder.getScProductOrderNo());
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE2);
                customerRecord.setCreaterId(userEntity.getId());
                if (StringUtils.isNotEmpty(map.get("remark"))){
                customerRecord.setContent(map.get("remark").toString());
                }
                MQMessageSendUtil.ucMessageSend(customerRecord);

                //提交之后，将订单信息同步到企大顺生产中心
                MQMessageSendUtil.qdsMessageSend(productOrder, null,  userEntity);

                String[] msgs = new String[]{productOrder.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                List<UserEntity> users = new ArrayList<>();
                users.add(flower);//接收人
                commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_SC_TURN_OVER");//移交模板
                String msgConent="您好，您的客户"+productOrder.getCustomerName()+"订单"+productOrder.getOrderNo()+"办理的"+productOrder.getScProductOrderNo()+"业务，订单移交给"+flower.getRealName()+",请及时确认处理";
                commonService.sendQgjMessage(productOrder.getOrderId(),productOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * <p>@Description 保存证书/资质预定</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/28 0028 9:04 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void saveCertificateAdvance(Long certificateId,String certificateNo, Long orderId, Integer type) {
        BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(certificateId);
        if (StringUtils.isEmpty(certificateNo)){
            certificateNo = baseCredential.getCertificateNo();
        }
        GeneralCertificate generalCertificate = new GeneralCertificate();
        if (type == 1) {
            ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到证书的基础信息,请刷新列表！");
            generalCertificate = generalCredentialService.findCredentialById(certificateId);
        } else if (type == 2) {
            ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到资质的基础信息,请刷新列表！");
        }
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(orderId);
        //完结和结项不能预定证书  加上  暂停和退单的三个状态
        boolean statusFlag = true;
        String status = productOrder.getStatus();
//        if (ScProductConstant.SC_ORDER_OVER.equals(status) || ScProductConstant.SC_ORDER_OVER_OVERDUE.equals(status)
//                || ScProductConstant.SC_ORDER_OVER_FORCE.equals(status) || ScProductConstant.SC_ORDER_JUNCTIONS.equals(status)
//                || ScProductConstant.SC_ORDER_SUSPEND.equals(status) || ScProductConstant.SC_ORDER_CHARGEBACK_DSH.equals(status)
//                || ScProductConstant.SC_ORDER_CHARGEBACK_TDBH.equals(status) || ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK.equals(status)) {
//            statusFlag = false; //这些不能预定证书
//        }
        if (ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK.equals(status)) {
            statusFlag = false; //这些不能预定证书
        }
        String certificateStatus = baseCredential.getCertificateStatus();//先验证下能不能预定
        // 保存操作日志
        SystemRecord systemRecord = new SystemRecord();
        //操作中间表的操作日志
        SystemRecord cpSystemRecord = new SystemRecord();
        //预约表的操作日志
        SystemRecord resSystemRecord = new SystemRecord();
        //预定完了往预约表插一条状态为已预定的数据
        ProductReservation productReservation = new ProductReservation();//预约实体
        if (type == 1) {//这里证书预定
            ValidateUtils.isTrue(statusFlag, ProductOrderExcption.class, "当前生产订单状态不能绑定证书,请刷新列表信息!");
            // ValidateUtils.isTrue(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE.equals(certificateStatus), ProductOrderExcption.class, "当前证书不是未使用状态,无法预定,请刷新列表!");
            baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION);//已预定
            systemRecord.setRemarks("生产订单预定证书");
            cpSystemRecord.setRemarks("生产订单预定证书");
            resSystemRecord.setRemarks("生产订单预定证书");
            //预约的信息
            productReservation.setType(CredentialConstant.GENERAL_CREDENTIAL);//证书
        } else if (type == 2) {//这里资质预定
            ValidateUtils.isTrue(statusFlag, ProductOrderExcption.class, "当前生产订单状态不能绑定资质,请刷新列表信息!");
            ValidateUtils.isTrue(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_ONE.equals(certificateStatus), ProductOrderExcption.class, "当前资质不是未使用状态,无法预定,请刷新列表!");
            baseCredential.setCertificateStatus(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_TWO);//已预定
            systemRecord.setRemarks("生产订单预定资质");
            cpSystemRecord.setRemarks("生产订单预定资质");
            resSystemRecord.setRemarks("生产订单预定资质");
            //预约的信息
            productReservation.setType(CredentialConstant.ZZ_CREDENTIAL);//资质
        }
        baseCredential.setScOrderId(orderId);//绑定
        baseCredential.setScOrderNo(productOrder.getScProductOrderNo());
        this.updateOpt(baseCredential, userEntity);//修改信息
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改基础表
        Map<String, Object> specialMap = new HashMap<>();
        specialMap.put("certificateId", baseCredential.getId());
        List<Map> storageList = certificateSpecialtyDao.findByCondition(specialMap);//根据证书ID查中间表
        Map storageMap = new HashMap();
        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();
        if (storageList != null && !storageList.isEmpty()) {
            for (Map storage : storageList) {
                String certificateCode = storage.get("certificateCode").toString();
                storageMap.put("certificateCode", certificateCode);
                StorageCapacity storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                // 预订量 + 1
                storageCapacity.setReserveNumbers(storageCapacity.getReserveNumbers() + 1);
                //在库容量 -1
                storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() - 1);
                //暂定为随便写一个
                productReservation.setCertificateNo(storageCapacity.getCertificateCode());
                newStorageCapacityList.add(storageCapacity);
            }
        }
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改证书基础表
        this.updateOpt(productOrder, userEntity);

        //预约的实体相关
        productReservation.setId(DggKeyWorker.nextId());
        productReservation.setCertificateId(baseCredential.getId());//证书ID
        productReservation.setScProductId(productOrder.getId());//生产订单ID
        productReservation.setScProductNo(productOrder.getScProductOrderNo());
        productReservation.setStatus(CredentialConstant.PRODUCT_RESERVATION_STATUS_SUCCESS);//由新增预约变成的已预定
        this.saveOpt(productReservation, userEntity);
        productReservationDao.insert(productReservation);
        resSystemRecord.setSource("2");//生产
        resSystemRecord.setOperateType("10");// 操作类型  预定
        resSystemRecord.setWorkTableName("zzsc_product_reservation");
        resSystemRecord.setWorkId(productReservation.getId());
        resSystemRecord.setWorkNo(certificateNo);
        resSystemRecord.setCertificateCode(certificateNo);
        systemRecordService.save(resSystemRecord);

        systemRecord.setSource("2");//生产
        systemRecord.setOperateType("10");// 操作类型  预定
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setWorkId(productOrder.getId());
        systemRecordService.save(systemRecord);
        //预定证书往 证书和生产的中间表写入数据
        Long certifateProductId = certificateProductService.saveCertifateProduct(certificateId, orderId);
        cpSystemRecord.setSource("2");//生产
        cpSystemRecord.setOperateType("10");// 操作类型:  预定
        cpSystemRecord.setWorkTableName("zz_certificate_product");
        cpSystemRecord.setWorkId(certifateProductId);
        systemRecordService.save(cpSystemRecord);
        //调用发送消息公共方法
        // 证书{0}已经于{1}由{2}成功预订
        try {//不让影响其他功能,发送失败就算了
            String[] msgs = new String[]{null==generalCertificate.getPersonalName()?"":generalCertificate.getPersonalName(),null == generalCertificate.getCertificateName() ? "": generalCertificate.getCertificateName(),baseCredential.getCertificateNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"), productOrder.getScProductOrderNo()};
            List<UserEntity> users = new ArrayList<>();
            if (type == 1) {//证书
                String[] codes = new String[]{"ZZSC_ZS_ADMIN", "ZZSC_ZS_SUPER_ADMIN"};
                users = userService.findUserByRoleCodesAndOrgs(codes, 0, baseCredential.getSignOrgId());
            } else if (type == 2) {//资质
                String[] codes = new String[]{"ZZSC_ZZ_ADMIN", "ZZSC_ZZ_SUPER_ADMIN"};
                users = userService.findUserByRoleCodesAndOrgs(codes, 0, baseCredential.getSignOrgId());
            }
            if (users == null) {
                users = new ArrayList<>();
            }
            List<Assistant> assistants = this.queyScAssistantList(productOrder.getId());//协单人员
            UserEntity assistUser;
            for (Assistant assistant : assistants) {
                assistUser = new UserEntity();
                assistUser.setId(assistant.getAssistUserId());
                users.add(assistUser);
            }
            if (productOrder.getFlowUserId() != null) {
                users.add(userService.findUserById(productOrder.getFlowUserId()));//流程人员
            }
            commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_ZS_RESERVATION");//预定模板
            if (type == 1) {
                String haveName=null==generalCertificate.getPersonalName()?"":generalCertificate.getPersonalName();
                String certificateName= null == generalCertificate.getCertificateName() ? "": generalCertificate.getCertificateName();
                String msgConent="您好，您的客户"+productOrder.getCustomerName()+"订单"+productOrder.getOrderNo()+"办理的"
                        +productOrder.getScProductOrderNo()+"业务，已预订 "+haveName+" "+certificateName+"证书";
                commonService.sendQgjMessage(productOrder.getOrderId(),productOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
            }
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(productOrder.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(productOrder.getId());
            customerRecord.setTableNo(productOrder.getScProductOrderNo());
            if (type==1){
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE23);
                customerRecord.setContent("证书预定");
            }
            if (type==2){
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE24);
                customerRecord.setContent("资质预定");
            }
            customerRecord.setCreaterId(userEntity.getId());
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(productOrder, null,  userEntity);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <p>@Description 取消预定</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/28 0028 14:28 创建时间</p>
     * <p>@return</p>
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void cancelAdvanceCertificate(Long certificateId,String certificateNo, Long orderId, Integer type) {//type 1是证书,2是资质
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(orderId);
        BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(certificateId);
        // 是否能匹配证书
        Boolean canProductReservation = false;
        if (type == 1) {
            ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到该证书,请刷新列表重试!");
        } else if (type == 2) {
            ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到该资质,请刷新列表重试!");
        }
        String certificateStatus = baseCredential.getCertificateStatus();//先验证下能不能取消预定
        if (type == 1) {
            ValidateUtils.isTrue(CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION.equals(certificateStatus), ProductOrderExcption.class, "当前证书不是已预定状态,无法取消预定,请刷新列表!");
            baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE);//改成未使用
            CredentialInfo credentialInfo = credentialInfoService.getCredentialInfoById(baseCredential.getId());
            GeneralCertificate generalCertificate = generalCredentialService.findCredentialById(baseCredential.getId());
            if(CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION.equals(certificateStatus) && CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_OUT.equals(credentialInfo.getLibraryStatus())&& "OUT_GOING_REASON_05".equals(generalCertificate.getOutgoingReason())
                    && "成都资质事业部".equals(productOrder.getProductOrgName())) {
                Map map = isMatchingPunish(productOrder, baseCredential);
                if (!map.isEmpty()) {
                    Integer code = matchingPunish(map, productOrder);
                    if (code == 0) {
                        productOrder.setMatchingPunishStatus(1);
                        this.updateOpt(productOrder, userEntity);
                        productOrderDao.updateByPrimaryKey(productOrder);
                        //发送扣罚消息
                        try {//不让影响其他功能
                            List<UserEntity> users = new ArrayList<>();
                            //扣罚人
                            UserEntity user = userService.findUserById(Long.valueOf(map.get("certificateUserId").toString()));
                            users.add(user);
                            String unit = map.containsKey("money") ? "金额" : "操行分";
                            String pulishCount = map.containsKey("money") ? map.get("money").toString() : map.get("points").toString();
                            String msg[] = new String[]{credentialInfo.getPersonalName(), credentialInfo.getCertificateName(), pulishCount, unit};
                            commonService.sendMsgByAsynchronous(users, msg, "ZZSC_ZS_MATCH_PUNISH");//匹配模板
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } else if (type == 2) {
            ValidateUtils.isTrue(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_TWO.equals(certificateStatus), ProductOrderExcption.class, "当前资质不是已预定状态,无法取消预定,请刷新列表!");
            baseCredential.setCertificateStatus(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_ONE);//改成未使用
        }
        baseCredential.setScOrderId(null);//取消绑定
        baseCredential.setScOrderNo(null);
        this.updateOpt(baseCredential, userEntity);//修改信息
        Map<String, Object> specialMap = new HashMap<>();
        specialMap.put("certificateId", baseCredential.getId());
        List<Map> storageList = certificateSpecialtyDao.findByCondition(specialMap);//根据证书ID查中间表
        Map storageMap = new HashMap();
        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();
        if (storageList != null && !storageList.isEmpty()) {
            GeneralCertificate generalCertificate = null;
            if (type == 1) {
                // 验证当前证书是否已经过期并且超期类型是证书过期
                generalCertificate = generalCredentialService.findCredentialById(baseCredential.getId());
            }

            for (Map storage : storageList) {
                String certificateCode = storage.get("certificateCode").toString();
                storageMap.put("certificateCode", certificateCode);
                StorageCapacity storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                // 预订量 - 1
                storageCapacity.setReserveNumbers(storageCapacity.getReserveNumbers() - 1);

                //资质未超期在库量+1
                if (baseCredential.getGeneralType().equals(CredentialConstant.ZZ_CREDENTIAL)) {
                    if (2 == type && CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_ONE.equals(baseCredential.getOverdueStatus())) {
                        storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                        canProductReservation = true;
                    }
                } else { // 证书超期
                    // 过期并且是过期类型包含证书过期(并且在库)
                    if (CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN.equals(generalCertificate.getLibraryStatus()) && !("0".equals(generalCertificate.getOverdueStatus()) && generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL))) {
                        storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                        canProductReservation = true;
                    }
                }
                newStorageCapacityList.add(storageCapacity);

            }
        }
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
        this.updateOpt(productOrder, userEntity);
        // 保存操作日志
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setSource("2");//生产
        systemRecord.setOperateType("13");// 操作类型  取消预定
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setWorkId(productOrder.getId());
        if (type == 1) {
            systemRecord.setRemarks("生产订单取消预定证书");
        } else if (type == 2) {
            systemRecord.setRemarks("生产订单取消预定资质");
        }
        systemRecordService.save(systemRecord);
        //预约表的记录
        SystemRecord resSystemRecord = new SystemRecord();
        //查出证书/资质  生产中间表 删除
        Map<String, Object> cpMap = new HashMap<>();
        cpMap.put("baseId", certificateId);
        cpMap.put("scOrderId", orderId);
        List<CertificateProduct> certificateProducts = certificateProductDao.queryByParams(cpMap);
        if (certificateProducts != null && !certificateProducts.isEmpty()) {//把中间表的数据查出来删了,这里只会有一条
            for (CertificateProduct certificateProduct : certificateProducts) {
                //操作中间表的操作日志
                SystemRecord cpSystemRecord = new SystemRecord();
                cpSystemRecord.setSource("2");//生产
                cpSystemRecord.setOperateType("13");// 操作类型:  取消预定
                cpSystemRecord.setWorkTableName("zz_certificate_product");
                cpSystemRecord.setWorkId(certificateProduct.getId());
                cpSystemRecord.setCertificateCode(certificateNo);
                cpSystemRecord.setWorkNo(certificateNo);
                if (type == 1) {
                    cpSystemRecord.setRemarks("生产订单取消预定证书");
                    resSystemRecord.setRemarks("生产订单取消预定证书");
                } else if (type == 2) {
                    cpSystemRecord.setRemarks("生产订单取消预定资质");
                    resSystemRecord.setRemarks("生产订单取消预定资质");
                }
                systemRecordService.save(cpSystemRecord);
                certificateProductDao.deleteByPrimaryKey(certificateProduct.getId());
            }
        }
        //需要删除对应的预约信息
        Map cerMap = new HashMap<String, Object>() {{
            put("certificateId", baseCredential.getId());
        }};
        List<ProductReservation> productReservations = productReservationDao.queryReservationByProduct(cerMap);
        if (productReservations != null && !productReservations.isEmpty()) {
            for (ProductReservation productReservation : productReservations) {//只有一个
                resSystemRecord.setSource("2");//生产
                resSystemRecord.setOperateType("13");// 操作类型  取消预定
                resSystemRecord.setWorkTableName("zzsc_product_reservation");
                resSystemRecord.setWorkId(productReservation.getId());
                systemRecordService.save(resSystemRecord);
                productReservationDao.deleteByPrimaryKey(productReservation.getId());
            }
        }
        //查询是否有别的生产订单预约
        BaseCredential newBaseCredential = null;
        if (canProductReservation) {
            newBaseCredential = generalCredentialService.boundProductReservation(certificateId, newStorageCapacityList, false);
        }
        if (newBaseCredential == null) {//这是里面传出来 表示进行过修改了
            baseCredentialDao.updateByPrimaryKey(baseCredential);//修改证书基础表
        }
    }

    /**
     * <p>@Description 保存匹配</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/28 0028 15:18 创建时间</p>
     * <p>@return</p>
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveMatchCertificate(Long certificateId,String certificateNo, Long orderId, Integer type) {//type 1是证书,2是资质
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(orderId);
        BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(certificateId);
        if (StringUtils.isEmpty(certificateNo)){
            certificateNo = baseCredential.getCertificateNo();
        }
        GeneralCertificate generalCertificate = new GeneralCertificate();

        if (type == 1) {
            ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到该证书,请刷新列表重试!");
            generalCertificate = generalCredentialService.findCredentialById(baseCredential.getId());
        } else if (type == 2) {
            ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到该资质,请刷新列表重试!");
        }
        //预约表的记录
        SystemRecord resSystemRecord = new SystemRecord();
        String certificateStatus = baseCredential.getCertificateStatus();//先验证下能不能 匹配
        if (type == 1) {
            CredentialInfo credentialInfo = credentialInfoService.getCredentialInfoById(baseCredential.getId());
            // 验证预定状态 已废弃
            //ValidateUtils.isTrue(CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION.equals(certificateStatus), ProductOrderExcption.class, "当前证书不是已预定状态,无法匹配,请刷新列表!");
            //ValidateUtils.isTrue(CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_OUT.equals(credentialInfo.getLibraryStatus()), ProductOrderExcption.class, "当前证书未出库,无法匹配,请先出库!");
            baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH);//改成已匹配
            resSystemRecord.setRemarks("生产订单匹配证书");
            if(CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION.equals(certificateStatus) && CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_OUT.equals(credentialInfo.getLibraryStatus())&& "OUT_GOING_REASON_05".equals(generalCertificate.getOutgoingReason())
                    && "成都资质事业部".equals(productOrder.getProductOrgName())) {
                Map map = isMatchingPunish(productOrder, baseCredential);
                if (!map.isEmpty()) {
                    Integer code = matchingPunish(map, productOrder);
                    if (code == 0) {
                        productOrder.setMatchingPunishStatus(1);
                        this.updateOpt(productOrder, userEntity);
                        productOrderDao.updateByPrimaryKey(productOrder);
                        //发送扣罚消息
                        try {//不让影响其他功能
                            List<UserEntity> users = new ArrayList<>();
                            //扣罚人
                            UserEntity user = userService.findUserById(Long.valueOf(map.get("certificateUserId").toString()));
                            users.add(user);
                            String unit = map.containsKey("money") ? "金额" : "操行分";
                            String pulishCount = map.containsKey("money") ? map.get("money").toString() : map.get("points").toString();
                            String msg[] = new String[]{credentialInfo.getPersonalName(), credentialInfo.getCertificateName(), pulishCount, unit};
                            commonService.sendMsgByAsynchronous(users, msg, "ZZSC_ZS_MATCH_PUNISH");//匹配模板
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        } else if (type == 2) {
            ValidateUtils.isTrue(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_TWO.equals(certificateStatus), ProductOrderExcption.class, "当前资质不是已预定状态,无法匹配,请刷新列表!");
            baseCredential.setCertificateStatus(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_THREE);//改成已匹配
            resSystemRecord.setRemarks("生产订单匹配资质");
        }
        this.updateOpt(baseCredential, userEntity);//修改信息
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改基础表
        Map<String, Object> specialMap = new HashMap<>();
        specialMap.put("certificateId", baseCredential.getId());
        List<Map> storageList = certificateSpecialtyDao.findByCondition(specialMap);//根据证书ID查中间表
        Map storageMap = new HashMap();
        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();
        if (storageList != null && !storageList.isEmpty()) {
            for (Map storage : storageList) {
                String certificateCode = storage.get("certificateCode").toString();
                storageMap.put("certificateCode", certificateCode);
                StorageCapacity storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                // 预订量 - 1
                storageCapacity.setReserveNumbers(storageCapacity.getReserveNumbers() - 1);
                // 匹配量 + 1
                storageCapacity.setMatchNumbers(storageCapacity.getMatchNumbers() + 1);
                newStorageCapacityList.add(storageCapacity);
            }
        }
        //修改库容量
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改证书基础表
        this.updateOpt(productOrder, userEntity);
        //需要修改对应的证书预约状态
        Map cerMap = new HashMap<String, Object>() {{
            put("certificateId", baseCredential.getId());
        }};
        List<ProductReservation> productReservations = productReservationDao.queryReservationByProduct(cerMap);
        if (productReservations != null && !productReservations.isEmpty()) {
            for (ProductReservation productReservation : productReservations) {
                resSystemRecord.setSource("2");//生产
                resSystemRecord.setOperateType("11");// 操作类型  匹配
                resSystemRecord.setWorkTableName("zzsc_product_reservation");
                resSystemRecord.setWorkId(productReservation.getId());
                resSystemRecord.setWorkNo(certificateNo);
                resSystemRecord.setCertificateCode(certificateNo);
                systemRecordService.save(resSystemRecord);
                productReservation.setStatus(CredentialConstant.PRODUCT_RESERVATION_STATUS_MATCH);//修改预约状态为已匹配
                productReservationDao.updateByPrimaryKey(productReservation);
            }
        }
        // 保存操作日志
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setSource("2");//生产
        systemRecord.setOperateType("11");// 操作类型  匹配
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setWorkId(productOrder.getId());
        if (type == 1) {
            systemRecord.setRemarks("生产订单匹配证书");
        } else if (type == 2) {
            systemRecord.setRemarks("生产订单匹配资质");
        }
        systemRecordService.save(systemRecord);
        //调用发送消息公共方法
        // 证书{0}已经于{1}由{2}成功匹配，请及时查看！
        try {//不让影响其他功能,发送失败就算了
            String[] msgs = new String[]{generalCertificate.getPersonalName(),generalCertificate.getCertificateName(),baseCredential.getCertificateNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"), productOrder.getScProductOrderNo()};
            List<UserEntity> users = new ArrayList<>();
            if (type == 1) {//证书
                String[] codes = new String[]{"ZZSC_ZS_ADMIN", "ZZSC_ZS_SUPER_ADMIN"};
                users = userService.findUserByRoleCodesAndOrgs(codes, 0, baseCredential.getSignOrgId());
            } else if (type == 2) {//资质
                String[] codes = new String[]{"ZZSC_ZZ_ADMIN", "ZZSC_ZZ_SUPER_ADMIN"};
                users = userService.findUserByRoleCodesAndOrgs(codes, 0, baseCredential.getSignOrgId());
            }
            if (users == null) {
                users = new ArrayList<>();
            }
            List<Assistant> assistants = this.queyScAssistantList(productOrder.getId());//协单人员
            UserEntity assistUser;
            for (Assistant assistant : assistants) {
                assistUser = new UserEntity();
                assistUser.setId(assistant.getAssistUserId());
                users.add(assistUser);
            }
            if (productOrder.getFlowUserId() != null) {
                users.add(userService.findUserById(productOrder.getFlowUserId()));//流程人员
            }
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(productOrder.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(productOrder.getId());
            customerRecord.setTableNo(productOrder.getScProductOrderNo());
            if(type == 1){
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE18);
                customerRecord.setContent("证书匹配");
            }
            if (type == 2){
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE19);
                customerRecord.setContent("资质匹配");
            }
            customerRecord.setCreaterId(userEntity.getId());
            MQMessageSendUtil.ucMessageSend(customerRecord);

            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(productOrder, null,  userEntity);

            //企管家消息发送
            commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_ZS_MATCH");//匹配模板
            String msgConent="您好,您的客户"+productOrder.getCustomerName()+"订单"+productOrder.getOrderNo()+"办理的"
                    +productOrder.getScProductOrderNo()+"业务，已匹配 "+generalCertificate.getPersonalName()+" "
                    +generalCertificate.getCertificateName()+"证书";
            commonService.sendQgjMessage(productOrder.getOrderId(),productOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 预约并匹配 龙
     */
    @Transactional
    public void saveAdvanceMatchCertificate(Long certificateId,String certificateNo, Long orderId, Long underOrderId){
        BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(certificateId);
        if(StringUtils.isNotEmpty(baseCredential.getScOrderNo())){
            throw new CommonExcption("该证书已匹配！");
        }
        if (StringUtils.isEmpty(certificateNo)){
            certificateNo = baseCredential.getCertificateNo();
        }
        ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到证书的基础信息,请刷新列表！");
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(orderId);
        //完结和结项不能预定证书  加上  暂停和退单的三个状态
        boolean statusFlag = true;
        String status = productOrder.getStatus();
        if (ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK.equals(status)) {
            statusFlag = false; //这些不能预定证书
        }
        // 保存操作日志
        SystemRecord systemRecord = new SystemRecord();
        //操作中间表的操作日志
        SystemRecord cpSystemRecord = new SystemRecord();
        //预约表的操作日志
        SystemRecord resSystemRecord = new SystemRecord();
        //预定完了往预约表插一条状态为已预定的数据
        ProductReservation productReservation = new ProductReservation();//预约实体
        ValidateUtils.isTrue(statusFlag, ProductOrderExcption.class, "当前生产订单状态不能绑定证书,请刷新列表信息!");
        baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH);//已匹配
        systemRecord.setRemarks("生产订单预定证书");
        cpSystemRecord.setRemarks("生产订单预定证书");
        resSystemRecord.setRemarks("生产订单预定证书");
        //预约的信息
        productReservation.setType(CredentialConstant.GENERAL_CREDENTIAL);//证书
        baseCredential.setScOrderId(orderId);//绑定
        baseCredential.setScOrderNo(productOrder.getScProductOrderNo());
        this.updateOpt(baseCredential, userEntity);//修改信息
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改基础表
        Map<String, Object> specialMap = new HashMap<>();
        specialMap.put("certificateId", baseCredential.getId());
        List<Map> storageList = certificateSpecialtyDao.findByCondition(specialMap);//根据证书ID查中间表
        Map storageMap = new HashMap();
        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();
        if (storageList != null && !storageList.isEmpty()) {
            for (Map storage : storageList) {
                String certificateCode = storage.get("certificateCode").toString();
                storageMap.put("certificateCode", certificateCode);
                StorageCapacity storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                //在库容量 -1
                storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() - 1);
                // 匹配量 + 1
                storageCapacity.setMatchNumbers(storageCapacity.getMatchNumbers() + 1);
                //暂定为随便写一个
                productReservation.setCertificateNo(storageCapacity.getCertificateCode());
                newStorageCapacityList.add(storageCapacity);
            }
        }
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改证书基础表
        this.updateOpt(productOrder, userEntity);
        //预约的实体相关
        productReservation.setId(DggKeyWorker.nextId());
        productReservation.setCertificateId(baseCredential.getId());//证书ID
        productReservation.setScProductId(productOrder.getId());//生产订单ID
        productReservation.setScProductNo(productOrder.getScProductOrderNo());
        productReservation.setStatus(CredentialConstant.PRODUCT_RESERVATION_STATUS_MATCH);//由新增预约变成的已匹配
        this.saveOpt(productReservation, userEntity);
        productReservationDao.insert(productReservation);
        Map map = new HashMap();
        map.put("orderId",productOrder.getOrderId());
        map.put("orderBusId",productOrder.getOrderBusId());
        List<UnderOder> underOderList = underOrderDao.selectUnderOrderList(map);
        int generalCertificateCount = generalCredentialService.queryGertificateCountByScOrderId(productOrder.getId());
        int underOrderCount = 0;
        for(UnderOder underOder:underOderList){
            underOrderCount += underOder.getCount();
        }
        if(generalCertificateCount > (underOrderCount - 1)){
            productOrder.setMatchingStatus(ScProductConstant.MATCHED);
        }else{
            productOrder.setMatchingStatus(ScProductConstant.MATCHING);
        }
        productOrderDao.updateByPrimaryKey(productOrder);
    }

    /**
     * <p>@Description 保存证书预约</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/28 0028 16:13 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void saveAppointmentCertificate(Map param) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(param.get("scOrderId"), ProductOrderExcption.class, "生产订单ID为空,请刷新页面重试！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(Long.valueOf(param.get("scOrderId").toString()));
        //完结和结项不能预定证书  加上  暂停和退单的三个状态
        boolean statusFlag = true;
        String status = productOrder.getStatus();
        if (ScProductConstant.SC_ORDER_OVER.equals(status) || ScProductConstant.SC_ORDER_OVER_OVERDUE.equals(status)
                || ScProductConstant.SC_ORDER_OVER_FORCE.equals(status) || ScProductConstant.SC_ORDER_JUNCTIONS.equals(status)
                || ScProductConstant.SC_ORDER_SUSPEND.equals(status) || ScProductConstant.SC_ORDER_CHARGEBACK_DSH.equals(status)
                || ScProductConstant.SC_ORDER_CHARGEBACK_TDBH.equals(status) || ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK.equals(status)) {
            statusFlag = false; //这些不能预约证书
        }
        ValidateUtils.isTrue(statusFlag, ProductOrderExcption.class, "当前生产订单状态不能预约证书,请刷新列表信息!");
        // 验证证书类型并将证书绑定证书基本类型
        Long userSybId = commonService.findUserSyb(userEntity);//查事业部ID
        Map<String, Object> storageMap = new HashMap<>();
        storageMap.put("certificateTypeId", param.get("certificateTypeHigh"));//类型
        storageMap.put("certificateSpecialty", param.get("certificateSpecialtysHigh"));//专业
        storageMap.put("certificateLevel", param.get("certificateLevelHigh"));//等级
        storageMap.put("applicationScope", param.get("applicationScopesHigh"));//适用范围
        storageMap.put("certificateArea", param.get("certificateArea"));//地区
        storageMap.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);//证书种类  普通证书和资质
        storageMap.put("signOrgId", userSybId);//证书种类  普通证书和资质
        //判断证书基本类型是否存在  不存在则添加
        List<StorageCapacity> storageCapacityList = storageCapacityService.verificationStorageCapacity(storageMap);
        ProductReservation productReservation;
        // 保存操作日志
        SystemRecord systemRecord;
        SystemRecord systemRecordOrder;
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();
        if (storageCapacityList != null && !storageCapacityList.isEmpty()) {
            for (StorageCapacity storageCapacity : storageCapacityList) {//这里是一对一 只会有一个
                productReservation = new ProductReservation();//预约实体
                productReservation.setId(DggKeyWorker.nextId());
                productReservation.setScProductId(productOrder.getId());//生产订单ID
                productReservation.setScProductNo(productOrder.getScProductOrderNo());
                productReservation.setCertificateNo(storageCapacity.getCertificateCode());
                productReservation.setType(CredentialConstant.GENERAL_CREDENTIAL);//证书
                productReservation.setStatus(CredentialConstant.PRODUCT_RESERVATION_STATUS_RESERVATION);//新增预约
                this.saveOpt(productReservation, userEntity);
                productReservationDao.insert(productReservation);
                // 预约量 +1
                storageCapacity.setOrderNumbers(storageCapacity.getOrderNumbers() + 1);
                newStorageCapacityList.add(storageCapacity);
                // 保存操作日志 生产订单表的
                systemRecord = new SystemRecord();
                systemRecord.setSource("2");//生产
                systemRecord.setOperateType("48");// 操作类型  预约
                systemRecord.setWorkTableName("zzsc_product_order");
                systemRecord.setWorkId(productOrder.getId());
                systemRecord.setRemarks("生产订单预约证书");
                systemRecordService.save(systemRecord);

                this.updateOpt(productOrder, userEntity);
                productOrderDao.updateByPrimaryKey(productOrder);

                // 保存操作日志 预约表的
                systemRecordOrder = new SystemRecord();
                systemRecordOrder.setSource("2");//生产
                systemRecordOrder.setOperateType("48");// 操作类型  预约
                systemRecordOrder.setWorkTableName("zzsc_product_reservation");
                systemRecordOrder.setWorkId(productReservation.getId());
                systemRecordOrder.setRemarks("生产订单预约证书");
                systemRecordService.save(systemRecordOrder);
            }
        }
        //修改库容量
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量

    }

    /**
     * <p>@Description 取消预约证书</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/29 0029 9:13 创建时间</p>
     * <p>@return</p>
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void cancelAppointmentCertificate(Long scOrderId, Long resevationId) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(scOrderId);
        ValidateUtils.strNotEmpty(productOrder, ProductOrderExcption.class, "未查询到该生产订单,请刷新页面重试！");
        ProductReservation productReservation = productReservationDao.selectByPrimaryKey(resevationId);
        //预约量 要减掉
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();//修改库容量
        Map<String, Object> storageMap = new HashMap<>();
        //判断证书基本类型是否存在  不存在则添加
        storageMap.put("certificateCode", productReservation.getCertificateNo());
        StorageCapacity storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
        //预约量 - 1
        storageCapacity.setOrderNumbers(storageCapacity.getOrderNumbers() - 1);
        newStorageCapacityList.add(storageCapacity);
        //修改库容量
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量

        String type = productReservation.getType();//拿出来判断是资质还是证书预约取消
        // 保存操作日志
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setSource("2");//生产
        systemRecord.setOperateType("16");// 操作类型  取消预约
        systemRecord.setWorkTableName("zzsc_product_reservation");
        systemRecord.setWorkId(resevationId);
        if (CredentialConstant.GENERAL_CREDENTIAL.equals(type)) {
            systemRecord.setRemarks("生产订单取消证书预约");
        } else if (CredentialConstant.ZZ_CREDENTIAL.equals(type)) {
            systemRecord.setRemarks("生产订单取消资质预约");
        }
        systemRecordService.save(systemRecord);
        this.updateOpt(productOrder, userEntity);
        productOrderDao.updateByPrimaryKey(productOrder);
        SystemRecord systemRecordOrder = new SystemRecord();
        systemRecordOrder.setSource("2");//生产
        systemRecordOrder.setOperateType("16");// 操作类型  取消预约
        systemRecordOrder.setWorkTableName("zzsc_product_order");
        systemRecordOrder.setWorkId(scOrderId);
        if (CredentialConstant.GENERAL_CREDENTIAL.equals(type)) {
            systemRecord.setRemarks("生产订单取消证书预约");
        } else if (CredentialConstant.ZZ_CREDENTIAL.equals(type)) {
            systemRecord.setRemarks("生产订单取消资质预约");
        }
        systemRecordService.save(systemRecordOrder);
        productReservationDao.deleteByPrimaryKey(resevationId);//删掉
    }

    /**
     * <p>@Description 保存资质预约</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/29 0029 11:23 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void saveAppointmentQualification(Map param) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(param.get("scProductId"), ProductOrderExcption.class, "生产订单ID为空,请刷新页面重试！");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(Long.valueOf(param.get("scProductId").toString()));
        //完结和结项不能预定证书  加上  暂停和退单的三个状态
        boolean statusFlag = true;
        String status = productOrder.getStatus();
        if (ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK.equals(status)) {
            statusFlag = false; //这些不能预约资质
        }
        ValidateUtils.isTrue(statusFlag, ProductOrderExcption.class, "当前生产订单状态不能预约资质,请刷新列表信息!");
        // 验证证书类型并将证书绑定证书基本类型
        Long userSybId = commonService.findUserSyb(userEntity);//查事业部ID
        Map<String, Object> storageMap = new HashMap<>();
        storageMap.put("certificateTypeId", param.get("certificateType"));//类型
        storageMap.put("certificateSpecialty", param.get("certificateName"));//资质名称
        storageMap.put("certificateLevel", param.get("certificateLevel"));//等级
        storageMap.put("applicationScope", param.get("applicationScope"));//适用范围
        storageMap.put("certificateArea", param.get("certificateArea"));//地区
        storageMap.put("generalType", CredentialConstant.ZZ_CREDENTIAL);//证书种类  普通证书和资质 这里为资质
        storageMap.put("signOrgId", userSybId);//事业部
        //判断证书基本类型是否存在  不存在则添加
        List<StorageCapacity> storageCapacityList = storageCapacityService.verificationStorageCapacity(storageMap);
        ProductReservation productReservation;
        // 保存操作日志
        SystemRecord systemRecord;
        SystemRecord systemRecordOrder;
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();//修改库容量
        if (storageCapacityList != null && !storageCapacityList.isEmpty()) {
            for (StorageCapacity storageCapacity : storageCapacityList) {//这里是一对一 只会有一个
                productReservation = new ProductReservation();//预约实体
                productReservation.setId(DggKeyWorker.nextId());
                productReservation.setScProductId(productOrder.getId());//生产订单ID
                productReservation.setScProductNo(productOrder.getScProductOrderNo());
                productReservation.setCertificateNo(storageCapacity.getCertificateCode());
                productReservation.setType(CredentialConstant.ZZ_CREDENTIAL);//资质
                productReservation.setStatus(CredentialConstant.PRODUCT_RESERVATION_STATUS_RESERVATION);//新增预约
                this.saveOpt(productReservation, userEntity);
                productReservationDao.insert(productReservation);
                // 预约量 +1
                storageCapacity.setOrderNumbers(storageCapacity.getOrderNumbers() + 1);
                newStorageCapacityList.add(storageCapacity);
                // 保存操作日志 生产订单表的
                systemRecord = new SystemRecord();
                systemRecord.setSource("2");//生产
                systemRecord.setOperateType("48");// 操作类型  预约
                systemRecord.setWorkTableName("zzsc_product_order");
                systemRecord.setWorkId(productOrder.getId());
                systemRecord.setRemarks("生产订单预约资质");
                systemRecordService.save(systemRecord);

                this.updateOpt(productOrder, userEntity);
                productOrderDao.updateByPrimaryKey(productOrder);
                // 保存操作日志 预约表的
                systemRecordOrder = new SystemRecord();
                systemRecordOrder.setSource("2");//生产
                systemRecordOrder.setOperateType("48");// 操作类型  预约
                systemRecordOrder.setWorkTableName("zzsc_product_reservation");
                systemRecordOrder.setWorkId(productReservation.getId());
                systemRecordOrder.setRemarks("生产订单预约资质");
                systemRecordService.save(systemRecordOrder);
            }
        }
        //修改库容量
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
    }


    /**
     * <p>@Description 保存证书使用</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/30 0030 14:30 创建时间</p>
     * <p>@return</p>
     */

    @Transactional
    public void saveCertificateSubordinate(Map param) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(param.get("certificateId"), ProductOrderExcption.class, "证书ID为空,请刷新页面重试!");
        ValidateUtils.strNotEmpty(param.get("scOrderId"), ProductOrderExcption.class, "生产订单ID为空,请刷新页面重试!");
        ValidateUtils.strNotEmpty(param.get("certificatePrice"), ProductOrderExcption.class, "使用价格不能为空!");
        ValidateUtils.strNotEmpty(param.get("affiliatedCompany"), ProductOrderExcption.class, "使用公司不能为空!");
        ValidateUtils.strNotEmpty(param.get("affiliatedStartTime"), ProductOrderExcption.class, "使用起始时间不能为空!");
        ValidateUtils.strNotEmpty(param.get("affiliatedExpireTime"), ProductOrderExcption.class, "使用结束时间不能为空!");
        Long certificateId = Long.valueOf(param.get("certificateId").toString());
        Long scOrderId = Long.valueOf(param.get("scOrderId").toString());
        GeneralCertificate generalCertificate = generalCredentialService.findCredentialById(certificateId);
        ValidateUtils.strNotEmpty(generalCertificate, ProductOrderExcption.class, "没有查询到此证书,请刷新页面信息!");
        ValidateUtils.isTrue(CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH.equals(generalCertificate.getCertificateStatus()), ProductOrderExcption.class, "当前证书不是已匹配状态,无法使用,请刷新页面信息!");
        //使用公司 使用起始时间 使用结束时间  (注意使用价格存在基本表)
        generalCertificate.setAffiliatedCompany(param.get("affiliatedCompany").toString());
        generalCertificate.setAffiliatedStartTime(DateUtil.stringToDate(param.get("affiliatedStartTime").toString(), "yyyy-MM-dd"));
        generalCertificate.setAffiliatedExpireTime(DateUtil.stringToDate(param.get("affiliatedExpireTime").toString(), "yyyy-MM-dd"));
        this.updateOpt(generalCertificate, userEntity);
        generalCertificateDao.updateByPrimaryKey(generalCertificate);//修改普通证书表
        // 保存操作日志 普通证书表
        SystemRecord generalSystemRecord = new SystemRecord();
        generalSystemRecord.setSource("2");//生产
        generalSystemRecord.setOperateType("12");// 操作类型  使用
        generalSystemRecord.setWorkTableName("zz_general_certificate");
        generalSystemRecord.setWorkId(generalCertificate.getGeneralCertificateId());
        generalSystemRecord.setWorkNo(param.get("certificateNo") == null ? generalCertificate.getCertificateNo() : param.get("certificateNo").toString());
        generalSystemRecord.setCertificateCode(param.get("certificateNo") == null ? generalCertificate.getCertificateNo() : param.get("certificateNo").toString());
        generalSystemRecord.setRemarks("生产订单使用证书");
        systemRecordService.save(generalSystemRecord);

        BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(certificateId);
        //使用价格  修改状态  已使用
        baseCredential.setCertificatePrice(new BigDecimal(param.get("certificatePrice").toString()));
        baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE);
        this.updateOpt(baseCredential, userEntity);
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改基础表为已使用
        Map<String, Object> specialMap = new HashMap<>();
        specialMap.put("certificateId", baseCredential.getId());
        List<Map> storageList = certificateSpecialtyDao.findByCondition(specialMap);//根据证书ID查中间表
        Map<String, Object> storageMap = new HashMap<>();
        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();
        if (storageList != null && !storageList.isEmpty()) {
            for (Map storage : storageList) {
                String certificateCode = storage.get("certificateCode").toString();
                storageMap.put("certificateCode", certificateCode);
                StorageCapacity storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                // 使用量 + 1
                storageCapacity.setHangUpNumbers(storageCapacity.getHangUpNumbers() + 1);
                // 匹配量 - 1
                storageCapacity.setMatchNumbers(storageCapacity.getMatchNumbers() - 1);
                newStorageCapacityList.add(storageCapacity);
            }
        }
        //修改库容量
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
        // 保存操作日志 基础表的
        SystemRecord baseSystemRecord = new SystemRecord();
        baseSystemRecord.setSource("2");//生产
        baseSystemRecord.setOperateType("12");// 操作类型  使用
        baseSystemRecord.setWorkTableName("zz_base_credential");
        baseSystemRecord.setWorkId(baseCredential.getId());
        baseSystemRecord.setRemarks("生产订单使用证书");
        systemRecordService.save(baseSystemRecord);

        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(scOrderId);
        this.updateOpt(productOrder, userEntity);
        SystemRecord systemRecord = new SystemRecord();
        // 保存操作日志 生产订单表的
        systemRecord.setSource("2");//生产
        systemRecord.setOperateType("12");// 操作类型  使用
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setWorkId(productOrder.getId());
        systemRecord.setRemarks("生产订单使用证书");
        systemRecordService.save(systemRecord);

        // 添加资金池使用记录
        capitalPoolCountService.addCapitalPoolCountRecord(baseCredential, userEntity, baseCredential.getCertificatePrice(), 1, null);

        //调用发送消息公共方法
        // 证书{0}已经于{1}由{2}成功使用，请及时查看！
        try {//不让影响其他功能,发送失败就算了
            String[] msgs = new String[]{generalCertificate.getPersonalName(),baseCredential.getCertificateName(),baseCredential.getCertificateNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"), productOrder.getScProductOrderNo()};
            String[] codes = new String[]{"ZZSC_ZS_ADMIN", "ZZSC_ZS_SUPER_ADMIN"};//证书管理员
            List<UserEntity> users = userService.findUserByRoleCodesAndOrgs(codes, 0, baseCredential.getSignOrgId());
            if (users == null) {
                users = new ArrayList<>();
            }
            List<Assistant> assistants = this.queyScAssistantList(productOrder.getId());//协单人员
            UserEntity assistUser;
            for (Assistant assistant : assistants) {
                assistUser = new UserEntity();
                assistUser.setId(assistant.getAssistUserId());
                users.add(assistUser);
            }
            if (productOrder.getFlowUserId() != null) {
                users.add(userService.findUserById(productOrder.getFlowUserId()));//流程人员
            }
            commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_ZS_AFFILIATED");//使用模板
            String personName=generalCertificate.getPersonalName()==null?"":generalCertificate.getPersonalName();
            String certifcateName=baseCredential.getCertificateName()==null?"":baseCredential.getCertificateName();
            String msgConent="您好,您的客户"+productOrder.getCustomerName()+"订单"+productOrder.getOrderNo()+"办理的"
                    +productOrder.getScProductOrderNo()+"业务，已使用 "+personName+" "+ certifcateName+"证书";
            commonService.sendQgjMessage(productOrder.getOrderId(),productOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(productOrder.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(productOrder.getId());
            customerRecord.setTableNo(productOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE25);
            customerRecord.setCreaterId(userEntity.getId());
            customerRecord.setContent("生产订单使用证书");
            MQMessageSendUtil.ucMessageSend(customerRecord);

            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(productOrder, null,  userEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * <p>@Description 取消匹配证书或者资质</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/30 0030 15:54 创建时间</p>
     * <p>@return</p>
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void cancelMatchCertificate(Map param) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(param.get("certificateId"), ProductOrderExcption.class, "证书或资质ID为空,请刷新页面重试!");
        ValidateUtils.strNotEmpty(param.get("scOrderId"), ProductOrderExcption.class, "生产订单ID为空,请刷新页面重试!");
        Integer type = Integer.valueOf(param.get("type").toString());//1 证书 2 资质
        Long certificateId = Long.valueOf(param.get("certificateId").toString());
        Long scOrderId = Long.valueOf(param.get("scOrderId").toString());
        BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(certificateId);
        // 保存操作日志 生产订单表的
        SystemRecord systemRecord = new SystemRecord();
        //预约表的记录
        SystemRecord resSystemRecord = new SystemRecord();
        //证书表的记录
        SystemRecord resSystemRecord1 = new SystemRecord();

        // 是否能匹配证书
        Boolean canProductReservation = false;
        if (type == 1) {//证书
            ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到此证书,请刷新页面信息!");
            ValidateUtils.isTrue(CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH.equals(baseCredential.getCertificateStatus()), ProductOrderExcption.class, "当前证书不是已匹配状态,无法取消匹配,请刷新页面信息!");
            systemRecord.setRemarks("生产订单取消匹配证书");
            resSystemRecord.setRemarks("生产订单取消匹配证书");
            resSystemRecord1.setRemarks("生产订单取消匹配证书");
            baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE);//改为未使用
        } else if (type == 2) {
            ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到此资质,请刷新页面信息!");
            ValidateUtils.isTrue(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_THREE.equals(baseCredential.getCertificateStatus()), ProductOrderExcption.class, "当前资质不是已匹配状态,无法取消匹配,请刷新页面信息!");
            systemRecord.setRemarks("生产订单取消匹配资质");
            resSystemRecord.setRemarks("生产订单取消匹配资质");
            resSystemRecord1.setRemarks("生产订单取消匹配资质");
            baseCredential.setCertificateStatus(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_ONE);//改为未使用
        }
        baseCredential.setScOrderId(null);//取消绑定
        baseCredential.setScOrderNo(null);
        this.updateOpt(baseCredential, userEntity);//修改信息
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改基础表
        Map<String, Object> specialMap = new HashMap<>();
        specialMap.put("certificateId", baseCredential.getId());
        List<Map> storageList = certificateSpecialtyDao.findByCondition(specialMap);//根据证书ID查中间表
        Map<String, Object> storageMap = new HashMap<>();
        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();
        if (storageList != null && !storageList.isEmpty()) {
            GeneralCertificate generalCertificate = null;
            if (type == 1) {
                // 验证当前证书是否已经过期并且超期类型是证书过期
                generalCertificate = generalCredentialService.findCredentialById(baseCredential.getId());
            }
            for (Map storage : storageList) {
                String certificateCode = storage.get("certificateCode").toString();
                storageMap.put("certificateCode", certificateCode);
                StorageCapacity storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                // 在库容量 +1
                //资质未超期在库量+1
                if (baseCredential.getGeneralType().equals(CredentialConstant.ZZ_CREDENTIAL)) {
                    if (2 == type && CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_ONE.equals(baseCredential.getOverdueStatus())) {
                        storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                        canProductReservation = true;
                    }
                } else { // 证书匹配
                    // 过期并且是过期类型包含证书过期(并且在库)
                    if (CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN.equals(generalCertificate.getLibraryStatus()) && !("0".equals(generalCertificate.getOverdueStatus()) && generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL))) {
                        storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                        canProductReservation = true;
                    }
                }

                // 匹配量 - 1
                storageCapacity.setMatchNumbers(storageCapacity.getMatchNumbers() - 1);
                newStorageCapacityList.add(storageCapacity);
            }
        }
        //修改库容量
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
        //查出证书/资质  生产中间表 删除
        Map<String, Object> cpMap = new HashMap<>();
        cpMap.put("baseId", certificateId);
        cpMap.put("scOrderId", scOrderId);
        List<CertificateProduct> certificateProducts = certificateProductDao.queryByParams(cpMap);
        //操作中间表的操作日志
        SystemRecord cpSystemRecord = new SystemRecord();
        if (certificateProducts != null && !certificateProducts.isEmpty()) {//把中间表的数据查出来删了,这里只会有一条
            for (CertificateProduct certificateProduct : certificateProducts) {
                cpSystemRecord.setSource("2");//生产
                cpSystemRecord.setOperateType("14");// 操作类型:  取消匹配
                cpSystemRecord.setWorkTableName("zz_certificate_product");
                cpSystemRecord.setWorkId(certificateProduct.getId());
                if (type == 1) {
                    cpSystemRecord.setRemarks("生产订单取消预定证书");
                } else if (type == 2) {
                    cpSystemRecord.setRemarks("生产订单取消预定资质");
                }
                systemRecordService.save(cpSystemRecord);
                certificateProductDao.deleteByPrimaryKey(certificateProduct.getId());
            }
        }
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(scOrderId);
        this.updateOpt(productOrder, userEntity);
        systemRecord.setSource("2");//生产
        systemRecord.setOperateType("14");// 操作类型  取消匹配
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setWorkId(productOrder.getId());
        systemRecordService.save(systemRecord);
        //需要删除对应的预约信息
        Map cerMap = new HashMap<String, Object>() {{
            put("certificateId", baseCredential.getId());
        }};
        List<ProductReservation> productReservations = productReservationDao.queryReservationByProduct(cerMap);
        if (productReservations != null && !productReservations.isEmpty()) {
            for (ProductReservation productReservation : productReservations) {//只有一条
                resSystemRecord.setSource("2");//生产
                resSystemRecord.setOperateType("14");// 操作类型  取消匹配
                resSystemRecord.setWorkTableName("zzsc_product_reservation");
                resSystemRecord.setWorkId(productReservation.getId());
                resSystemRecord1.setSource("2");//生产
                resSystemRecord1.setOperateType("14");// 操作类型  取消匹配
                resSystemRecord1.setWorkTableName("zzsc_product_reservation");
                resSystemRecord1.setWorkId(productReservation.getId());
                resSystemRecord1.setWorkNo(param.get("certificateNo").toString());
                resSystemRecord1.setCertificateCode(param.get("certificateNo").toString());
                systemRecordService.save(resSystemRecord);
                systemRecordService.save(resSystemRecord1);
                productReservationDao.deleteByPrimaryKey(productReservation.getId());
            }
        }
        //查询是否有别的生产订单预约
        BaseCredential newBaseCredential = null;
        if (canProductReservation) {
            newBaseCredential = generalCredentialService.boundProductReservation(certificateId, newStorageCapacityList, false);
        }
        if (newBaseCredential == null) {//没有传出来才修改  不然在里面进行过修改了
            baseCredentialDao.updateByPrimaryKey(baseCredential);//修改证书基础表
        }
    }

    /**
     * <p>@Description 证书取消使用</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/30 0030 19:00 创建时间</p>
     * <p>@return</p>
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void cancelSubordinateCertificate(Map param) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(param.get("certificateId"), ProductOrderExcption.class, "证书或资质ID为空,请刷新页面重试!");
        ValidateUtils.strNotEmpty(param.get("scOrderId"), ProductOrderExcption.class, "生产订单ID为空,请刷新页面重试!");
        Long certificateId = Long.valueOf(param.get("certificateId").toString());
        Long scOrderId = Long.valueOf(param.get("scOrderId").toString());
        BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(certificateId);
        ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到此证书,请刷新页面信息!");
        ValidateUtils.isTrue(CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE.equals(baseCredential.getCertificateStatus()), ProductOrderExcption.class, "当前证书不是已使用状态,无法取消使用,请刷新页面信息!");
        //清空基础表的 生产订单相关
        baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE);//改为未使用
        baseCredential.setScOrderId(null);//取消绑定
        baseCredential.setScOrderNo(null);
        baseCredential.setCertificatePrice(new BigDecimal(0.00));//清空使用价格
        this.updateOpt(baseCredential, userEntity);//修改信息
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改基础表
        // 保存操作日志 基础表的
        SystemRecord baseSystemRecord = new SystemRecord();
        baseSystemRecord.setSource("2");//生产
        baseSystemRecord.setOperateType("15");// 操作类型  取消使用
        baseSystemRecord.setWorkTableName("zz_base_credential");
        baseSystemRecord.setWorkId(baseCredential.getId());
        baseSystemRecord.setRemarks("生产订单取消使用");
        baseSystemRecord.setWorkNo(param.get("certificateNo").toString());
        baseSystemRecord.setCertificateCode(param.get("certificateNo").toString());
        systemRecordService.save(baseSystemRecord);

        //清空普通证书表的: 使用公司,使用金额,使用起始时间,使用结束时间
        GeneralCertificate generalCertificate = generalCredentialService.findCredentialById(certificateId);
        generalCertificate.setAffiliatedCompany(null);
        generalCertificate.setCertificatePrice(null);
        generalCertificate.setAffiliatedStartTime(null);
        generalCertificate.setAffiliatedExpireTime(null);
        //清空三类使用相关
        generalCertificate.setThreeAffiliatedCompany(null);
        generalCertificate.setThreeAffiliatedExpireTime(null);
        generalCertificate.setThreeAffiliatedStartTime(null);
        this.updateOpt(generalCertificate, userEntity);
        generalCertificateDao.updateByPrimaryKey(generalCertificate);
        // 保存操作日志 普通证书表
        SystemRecord generalSystemRecord = new SystemRecord();
        generalSystemRecord.setSource("2");//生产
        generalSystemRecord.setOperateType("15");// 操作类型  取消使用
        generalSystemRecord.setWorkTableName("zz_general_certificate");
        generalSystemRecord.setWorkId(generalCertificate.getGeneralCertificateId());
        generalSystemRecord.setRemarks("生产订单取消使用");
        systemRecordService.save(generalSystemRecord);

        Map<String, Object> specialMap = new HashMap<>();
        specialMap.put("certificateId", baseCredential.getId());
        List<Map> storageList = certificateSpecialtyDao.findByCondition(specialMap);//根据证书ID查中间表
        Map<String, Object> storageMap = new HashMap<>();
        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();

        // 是否能匹配证书
        Boolean canProductReservation = false;
        if (storageList != null && !storageList.isEmpty()) {
            // 验证当前证书是否已经过期并且超期类型是证书过期
            generalCertificate = generalCredentialService.findCredentialById(baseCredential.getId());
            for (Map storage : storageList) {
                String certificateCode = storage.get("certificateCode").toString();
                storageMap.put("certificateCode", certificateCode);
                StorageCapacity storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                // 如果证书未过期或者证书过期但是过期类型不是证书过期
                // 过期并且是过期类型包含证书过期(并且在库)
                if (CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN.equals(generalCertificate.getLibraryStatus()) && !("0".equals(generalCertificate.getOverdueStatus()) && generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL))) {
                    storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                    canProductReservation = true;
                }
                // 使用量 - 1
                storageCapacity.setHangUpNumbers(storageCapacity.getHangUpNumbers() - 1);
                newStorageCapacityList.add(storageCapacity);
            }
        }
        //修改库容量
        storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(scOrderId);
        this.updateOpt(productOrder, userEntity);
        productOrderDao.updateByPrimaryKey(productOrder);
        //查出证书/资质  生产中间表 删除
        Map<String, Object> cpMap = new HashMap<>();
        cpMap.put("baseId", certificateId);
        cpMap.put("scOrderId", scOrderId);
        List<CertificateProduct> certificateProducts = certificateProductDao.queryByParams(cpMap);
        //操作中间表的操作日志
        SystemRecord cpSystemRecord = new SystemRecord();
        if (certificateProducts != null && !certificateProducts.isEmpty()) {//把中间表的数据查出来删了,这里只会有一条
            for (CertificateProduct certificateProduct : certificateProducts) {
                cpSystemRecord.setSource("2");//生产
                cpSystemRecord.setOperateType("15");// 操作类型:  取消使用
                cpSystemRecord.setWorkTableName("zz_certificate_product");
                cpSystemRecord.setWorkId(certificateProduct.getId());
                systemRecordService.save(cpSystemRecord);
                certificateProductDao.deleteByPrimaryKey(certificateProduct.getId());
            }
        }
        // 保存操作日志 生产订单表的
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setSource("2");//生产
        systemRecord.setOperateType("15");// 操作类型  取消使用
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setWorkId(productOrder.getId());
        systemRecord.setRemarks("生产订单取消使用");
        systemRecordService.save(systemRecord);
        //预约表的记录
        SystemRecord resSystemRecord = new SystemRecord();
        //需要删除对应的预约信息
        Map cerMap = new HashMap<String, Object>() {{
            put("certificateId", baseCredential.getId());
        }};
        List<ProductReservation> productReservations = productReservationDao.queryReservationByProduct(cerMap);
        if (productReservations != null && !productReservations.isEmpty()) {
            for (ProductReservation productReservation : productReservations) {
                resSystemRecord.setRemarks("生产订单取消使用");
                resSystemRecord.setSource("2");//生产
                resSystemRecord.setOperateType("15");// 操作类型  取消使用
                resSystemRecord.setWorkTableName("zzsc_product_reservation");
                resSystemRecord.setWorkId(productReservation.getId());
                systemRecordService.save(resSystemRecord);
                productReservationDao.deleteByPrimaryKey(productReservation.getId());
            }
        }
        //查询是否有别的生产订单预约
        BaseCredential newBaseCredential = null;
        if (canProductReservation) {
            newBaseCredential = generalCredentialService.boundProductReservation(certificateId, newStorageCapacityList, false);

        }

        if (newBaseCredential == null) {//没有传出来才修改  不然在里面进行过修改了
            baseCredentialDao.updateByPrimaryKey(baseCredential);//修改证书基础表
        }
    }

    /**
     * <p>@Description 查资质转让审核人</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/31 0031 10:18 创建时间</p>
     * <p>@return</p>
     */
    public List<UserDTO> findUserListByQulificationAuditor() {
        //查询资质转让审核人
        Map<String, Object> params = new HashMap<>();
        List<Long> userIds = userService.findUserByRoleCode("ZZSC_ZZ_ADMIN");//资质管理员 ZZSC_ZZ_ADMIN  ???
        List<Long> superIds = userService.findUserByRoleCode("ZZSC_ZZ_SUPER_ADMIN");//资质超级管理员 ZZSC_ZZ_SUPER_ADMIN
        userIds.addAll(superIds);
        params.put("userIds", userIds);
        return userService.findUserDTOPage(params);
    }


    /**
     * <p>@Description 保存资质转让申请</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/30 0030 20:20 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void saveApplicationTransfer(Map param) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(param.get("certificateId"), ProductOrderExcption.class, "资质ID为空,请刷新页面重试!");
        ValidateUtils.strNotEmpty(param.get("scOrderId"), ProductOrderExcption.class, "生产订单ID为空,请刷新页面重试!");
        ValidateUtils.strNotEmpty(param.get("qualificationNewPrice"), ProductOrderExcption.class, "转让价格不能为空!");
        ValidateUtils.strNotEmpty(param.get("currentAuditerId"), ProductOrderExcption.class, "审核人不能为空!");
        ValidateUtils.strNotEmpty(param.get("makeOverCompany"), ProductOrderExcption.class, "转让后所属企业不能为空!");
        Long certificateId = Long.valueOf(param.get("certificateId").toString());
        Long scOrderId = Long.valueOf(param.get("scOrderId").toString());
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(scOrderId);
        BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(certificateId);
        ValidateUtils.strNotEmpty(baseCredential, ProductOrderExcption.class, "没有查询到此资质,请刷新页面信息!");
        ValidateUtils.isTrue(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_THREE.equals(baseCredential.getCertificateStatus()), ProductOrderExcption.class, "当前资质不是已匹配状态,无法申请资质转让,请刷新页面信息!");
        //修改基础表状态,新增转让价格
        baseCredential.setCertificateStatus(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_FOUR);//改为已申请转让
        BigDecimal qualificationNewPrice = new BigDecimal(param.get("qualificationNewPrice").toString());
        baseCredential.setCertificatePrice(qualificationNewPrice);//转让价格
        this.updateOpt(baseCredential, userEntity);//修改信息
        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改基础表
        // 保存操作日志 基础表的
        SystemRecord baseSystemRecord = new SystemRecord();
        baseSystemRecord.setSource("2");//生产
        baseSystemRecord.setOperateType("52");// 操作类型  资质申请转让
        baseSystemRecord.setWorkTableName("zz_base_credential");
        baseSystemRecord.setWorkId(baseCredential.getId());
        baseSystemRecord.setRemarks("生产订单资质转让申请");
        systemRecordService.save(baseSystemRecord);

        Map qualificationMap = qualificationDao.findById(baseCredential.getId());
        Qualification qualification = qualificationDao.selectByPrimaryKey(Long.valueOf(qualificationMap.get("id").toString()));
        String originalCompany = qualification.getCompanyName();//原所属企业
        qualification.setMakeOverCompany(param.get("makeOverCompany").toString());//转让后所属企业
        qualificationDao.updateByPrimaryKey(qualification);//更新资质表
        // 保存操作日志 资质表的
        SystemRecord quaSystemRecord = new SystemRecord();
        quaSystemRecord.setSource("2");//生产
        quaSystemRecord.setOperateType("52");// 操作类型  资质申请转让
        quaSystemRecord.setWorkTableName("zz_qualification");
        quaSystemRecord.setWorkId(qualification.getId());
        quaSystemRecord.setRemarks("生产订单资质转让申请");
        systemRecordService.save(quaSystemRecord);

        // 资质转让
        Map<String, Object> rpMap = new HashMap<>();
        Long userSybId = commonService.findUserSyb(userEntity);//查事业部ID
        rpMap.put("signOrgId", userSybId);//事业部
        rpMap.put("warningType", CredentialConstant.ZZ_CREDENTIAL);//资质
        rpMap.put("warningName", "REVIEW_PROGRESSION");//审核级数
        Map rpResultMap = systemConfigureService.querySingleWarning(rpMap);//获取审核级数
        ValidateUtils.strNotEmpty(rpResultMap.get("configValue"), ProductOrderExcption.class, "未获取到您的事业部对应的资质转让审核级数,请联系资质管理员进行设置!");
        QualificationTransfer qualificationTransfer = new QualificationTransfer();
        qualificationTransfer.setId(DggKeyWorker.nextId());
        qualificationTransfer.setBaseId(baseCredential.getId());
        qualificationTransfer.setAuditerStatus(CredentialConstant.TRANSFER_CHECK_PENDING);//待审核
        qualificationTransfer.setReviewProgression(Integer.valueOf(rpResultMap.get("configValue").toString()));//审核级数
        qualificationTransfer.setQualificationOldPrice(baseCredential.getReceiptPrice());
        qualificationTransfer.setQualificationNewPrice(qualificationNewPrice);//转让价格
        qualificationTransfer.setOriginalCompany(originalCompany);
        qualificationTransfer.setMakeOverCompany(param.get("makeOverCompany").toString());//转让后所属企业
        Long currentAuditerId = Long.valueOf(param.get("currentAuditerId").toString());
        qualificationTransfer.setCurrentAuditerId(currentAuditerId);
        UserEntity currentAuditer = userService.findUserById(currentAuditerId);
        qualificationTransfer.setCurrentAuditerName(currentAuditer.getRealName() + currentAuditer.getLoginName());
        qualificationTransfer.setCurrentAuditerOrgId(currentAuditer.getOrgId());//审核人部门
        Map org = cmsService.findOrg(currentAuditer.getOrgId());
        qualificationTransfer.setCurrentAuditerOrgName(org.get("name").toString());//审核人部门名字
        qualificationTransfer.setScOrderId(productOrder.getId());
        qualificationTransfer.setScOrderNo(productOrder.getScProductOrderNo());
        qualificationTransfer.setSubOrderId(productOrder.getOrderBusId());
        qualificationTransfer.setSubOrderNo(productOrder.getOrderBusNo());//子订单编号
        qualificationTransfer.setCustomerName(productOrder.getCustomerName());
        qualificationTransfer.setSignProduction(productOrder.getProductName());//产品
        qualificationTransfer.setSignUserId(productOrder.getSignUserId());
        qualificationTransfer.setSignUserName(productOrder.getSignUserName());
        qualificationTransfer.setSignUserOrgId(productOrder.getSignUserOrgId());
        qualificationTransfer.setSignUserOrgName(productOrder.getSignUserOrgName());
        qualificationTransfer.setSignUserDepartmentId(productOrder.getSignOrgId());
        qualificationTransfer.setSignUserDepartmentName(productOrder.getSignOrgName());
        qualificationTransfer.setCurrentReviewProgression(0);//当前默认零级
        this.saveOpt(qualificationTransfer, userEntity);
        qualificationTransferDao.insert(qualificationTransfer);//保存资质转让申请
        // 保存操作日志 资质转让表的
        SystemRecord transSystemRecord = new SystemRecord();
        transSystemRecord.setSource("2");//生产
        transSystemRecord.setOperateType("52");// 操作类型  资质申请转让
        transSystemRecord.setWorkTableName("zz_qualification_transfer");
        transSystemRecord.setWorkId(qualificationTransfer.getId());
        transSystemRecord.setRemarks("生产订单资质转让申请");
        systemRecordService.save(transSystemRecord);
        //暂时考虑不用修改容量

        this.updateOpt(productOrder, userEntity);
        // 保存操作日志 生产订单表的
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setSource("2");//生产
        systemRecord.setOperateType("52");// 操作类型  资质申请转让
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setWorkId(productOrder.getId());
        systemRecord.setRemarks("生产订单资质转让申请");
        systemRecordService.save(systemRecord);
        //调用发送消息公共方法
        // 证书{0}已经于{1}由{2}申请转让，请及时查看！
        try {//不让影响其他功能,发送失败就算了
            String[] msgs = new String[]{baseCredential.getCertificateNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"), productOrder.getScProductOrderNo()};
            String[] codes = new String[]{"ZZSC_ZZ_ADMIN", "ZZSC_ZZ_SUPER_ADMIN"};//资质管理员
            List<UserEntity> users = userService.findUserByRoleCodesAndOrgs(codes, 0, baseCredential.getSignOrgId());
            if (users == null) {
                users = new ArrayList<>();
            }
            List<Assistant> assistants = this.queyScAssistantList(productOrder.getId());//协单人员
            UserEntity assistUser;
            for (Assistant assistant : assistants) {
                assistUser = new UserEntity();
                assistUser.setId(assistant.getAssistUserId());
                users.add(assistUser);
            }
            if (productOrder.getFlowUserId() != null) {
                users.add(userService.findUserById(productOrder.getFlowUserId()));//流程人员
            }
            commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_ZS_TRANSFER_APPLY");//转让模板
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <p>@Description 查证书或资质预约量</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/6 0006 19:57 创建时间</p>
     * <p>@return</p>
     */
    public Integer queryReservationNumberByProduct(Map map) {
        return productReservationDao.queryReservationNumberByProduct(map);
    }

    /**
     * <p>@Description 退单审核完成后: 删除证书/资质 预约,取消 证书/资质 预定,取消证书/资质匹配,取消证书使用</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/6 0006 19:57 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void updateAllCertificateQualification(Long scProductId, UserEntity userEntity) {
        //删除预约
        this.deleteProductReservationBySc(scProductId, 0);
        //取消 预定/匹配/使用等
        this.cancelAdvanceBaseCredentialBySc(scProductId, userEntity);
    }

    /**
     * <p>@Description 删除证书/资质相关的预约信息</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/7 0007 8:53 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void deleteProductReservationBySc(Long scProductId, int type) {
        Map map = new HashMap<String, Object>() {{
            put("scProductId", scProductId);
            put("status", CredentialConstant.PRODUCT_RESERVATION_STATUS_RESERVATION);
        }};
        List<ProductReservation> productReservations = productReservationDao.queryReservationByProduct(map);
        Map<String, Object> storageMap = new HashMap<>();
        StorageCapacity storageCapacity;
        // 保存操作日志 预约表
        SystemRecord systemRecord = new SystemRecord();
        if (productReservations != null && !productReservations.isEmpty()) {
            for (ProductReservation productReservation : productReservations) {
                String genType = productReservation.getType();
                boolean flag = false;
                if (CredentialConstant.GENERAL_CREDENTIAL.equals(genType) && type == 1) {//证书
                    flag = true;
                } else if (CredentialConstant.ZZ_CREDENTIAL.equals(genType) && type == 2) {//资质
                    flag = true;
                }
                if (flag || type == 0) {//为零可以直接全部删除
                    //需要修改库容的证书基本类型
                    storageMap.put("certificateCode", productReservation.getCertificateNo());
                    storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                    // 预约量 -1
                    storageCapacity.setOrderNumbers(storageCapacity.getOrderNumbers() - 1);
                    //更新库容量
                    storageCapacityDao.updateByPrimaryKey(storageCapacity);
                    systemRecord.setSource("2");//生产
                    systemRecord.setOperateType("50");// 操作类型  删除
                    systemRecord.setWorkTableName("zzsc_product_reservation");
                    systemRecord.setWorkId(productReservation.getId());
                    if (type == 0) {
                        systemRecord.setRemarks("退单审核通过删除相关预约信息");
                    } else if (type == 1) {
                        systemRecord.setRemarks("取消证书预约");
                    } else if (type == 2) {
                        systemRecord.setRemarks("取消资质预约");
                    }
                    systemRecordService.save(systemRecord);
                    //删除预约
                    productReservationDao.deleteByPrimaryKey(productReservation.getId());
                }
            }
        }
    }

    /**
     * <p>@Description 取消 证书/资质 预定,匹配,使用等</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/7 0007 8:53 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void cancelAdvanceBaseCredentialBySc(Long scProductId, UserEntity userEntity) {
        Map map = new HashMap<String, Object>() {{
            put("scOrderId", scProductId);
        }};
        //查所有绑定的证书或者资质
        List<BaseCredential> baseCredentialList = baseCredentialDao.findCredentialListByScOrderId(map);
        Map<String, Object> storageMap = new HashMap<>();
        StorageCapacity storageCapacity;
        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();
        // 保存操作日志 基础证书表
        SystemRecord systemRecord = new SystemRecord();
        boolean handUpFlag = false;//是否使用
        // 是否能匹配证书
        Boolean canProductReservation = false;
        if (baseCredentialList != null && !baseCredentialList.isEmpty()) {
            for (BaseCredential baseCredential : baseCredentialList) {
                newStorageCapacityList.clear();//清空
                Map<String, Object> specialMap = new HashMap<>();
                specialMap.put("certificateId", baseCredential.getId());
                List<Map> storageList = certificateSpecialtyDao.findByCondition(specialMap);//根据证书ID查中间表
                String certificateStatus = baseCredential.getCertificateStatus();//证书或者资质的状态
                String generalType = baseCredential.getGeneralType();//证书或资质
                GeneralCertificate generalCertificate = null;
                if (CredentialConstant.GENERAL_CREDENTIAL.equals(generalType)) {
                    generalCertificate = generalCredentialService.findCredentialById(baseCredential.getId());

                }
                if (storageList != null && !storageList.isEmpty()) {
                    for (Map storage : storageList) {
                        handUpFlag = false;
                        String certificateCode = storage.get("certificateCode").toString();
                        storageMap.put("certificateCode", certificateCode);
                        storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                        //这里判断是资质或证书
                        if (CredentialConstant.GENERAL_CREDENTIAL.equals(generalType)) {
                            switch (certificateStatus) {
                                case CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION:
                                    // 预定量 - 1
                                    storageCapacity.setReserveNumbers(storageCapacity.getReserveNumbers() - 1);
                                    break;
                                case CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH:
                                    // 匹配量 - 1
                                    storageCapacity.setMatchNumbers(storageCapacity.getMatchNumbers() - 1);
                                    break;
                                case CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE:
                                    handUpFlag = true;
                                    // 使用量 - 1
                                    storageCapacity.setHangUpNumbers(storageCapacity.getHangUpNumbers() - 1);
                                    break;
                                default:
                            }
                            if (CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN.equals(generalCertificate.getLibraryStatus()) && !("0".equals(generalCertificate.getOverdueStatus()) && generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL))) {
                                storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                                canProductReservation = true;
                            }
                        } else if (CredentialConstant.ZZ_CREDENTIAL.equals(generalType)) {//资质
                            switch (certificateStatus) {
                                case CredentialConstant.CERTIFICATE_APTITUDE_STATUS_TWO:
                                    // 预定量 - 1
                                    storageCapacity.setReserveNumbers(storageCapacity.getReserveNumbers() - 1);
                                    break;
                                case CredentialConstant.CERTIFICATE_APTITUDE_STATUS_THREE:
                                    // 匹配量 - 1
                                    storageCapacity.setMatchNumbers(storageCapacity.getMatchNumbers() - 1);
                                    break;
                                case CredentialConstant.CERTIFICATE_APTITUDE_STATUS_FOUR:
                                    //匹配量-1
                                    storageCapacity.setMatchNumbers(storageCapacity.getMatchNumbers() - 1);
                                    break;
                                default:
                            }
                            if (CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_ONE.equals(baseCredential.getOverdueStatus())) {
                                storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                                canProductReservation = true;
                            }

                        }
                        newStorageCapacityList.add(storageCapacity);
                    }
                }
                boolean flag = true;
                if (CredentialConstant.ZZ_CREDENTIAL.equals(generalType) &&
                        CredentialConstant.CERTIFICATE_APTITUDE_STATUS_FIVE.equals(certificateStatus)) {
                    flag = false;//资质已转让状态不能清除关联
                }
                if (flag) {
                    //清空基础表的 生产订单相关
                    if (CredentialConstant.GENERAL_CREDENTIAL.equals(generalType)) {//普通证书
                        baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE);//改为未使用
                        systemRecord.setRemarks("退单审核通过取消证书绑定");
                    } else if (CredentialConstant.ZZ_CREDENTIAL.equals(generalType)) {//资质
                        baseCredential.setCertificateStatus(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_ONE);//改为未使用
                        systemRecord.setRemarks("退单审核通过取消资质绑定");
                    }
                    baseCredential.setScOrderId(null);//取消绑定
                    baseCredential.setScOrderNo(null);
                    if (handUpFlag) {//表示有使用需要清除使用相关信息
                        baseCredential.setCertificatePrice(new BigDecimal(0.00));//清空使用价格
                        //清空普通证书表的: 使用公司,使用金额,使用起始时间,使用结束时间
                        generalCertificate = generalCredentialService.findCredentialById(baseCredential.getId());
                        generalCertificate.setAffiliatedCompany(null);
                        generalCertificate.setCertificatePrice(null);
                        generalCertificate.setAffiliatedStartTime(null);
                        generalCertificate.setAffiliatedExpireTime(null);
                        this.updateOpt(generalCertificate, userEntity);
                        generalCertificateDao.updateByPrimaryKey(generalCertificate);
                    }
                    this.updateOpt(baseCredential, userEntity);//修改信息
                    systemRecord.setSource("2");//生产
                    systemRecord.setOperateType("2");// 操作类型  修改
                    systemRecord.setWorkTableName("zz_base_credential");
                    systemRecord.setWorkId(baseCredential.getId());
                    systemRecordService.save(systemRecord);
                    //修改库容量
                    storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
                    //查询是否有别的生产订单预约
                    BaseCredential newBaseCredential = null;
                    if (canProductReservation) {
                        newBaseCredential = generalCredentialService.boundProductReservation(baseCredential.getId(), newStorageCapacityList, false);
                    }

                    if (newBaseCredential == null) {//没有传出来才修改  不然在里面进行过修改了
                        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改证书基础表
                    }
                }
            }
        }
    }

    /**
     * <p>@Description 取消 证书/资质 预定</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/7 0007 18:39 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public void cancelAdvanceBySc(Long scProductId, UserEntity userEntity, int type) {
        Map<String, Object> reMap = new HashMap<String, Object>() {{
            put("scProductId", scProductId);
            put("status", CredentialConstant.PRODUCT_RESERVATION_STATUS_SUCCESS);
        }};
        if (type == 1) {
            reMap.put("type", CredentialConstant.GENERAL_CREDENTIAL);
        } else if (type == 2) {
            reMap.put("type", CredentialConstant.ZZ_CREDENTIAL);
        }
        //这里需要查出预定产生的预约信息删除
        SystemRecord reSystemRecord = new SystemRecord();
        List<ProductReservation> productReservations = productReservationDao.queryReservationByProduct(reMap);
        if (productReservations != null && !productReservations.isEmpty()) {
            for (ProductReservation productReservation : productReservations) {
                reSystemRecord.setSource("2");//生产
                reSystemRecord.setOperateType("50");// 操作类型  删除
                reSystemRecord.setWorkTableName("zzsc_product_reservation");
                reSystemRecord.setWorkId(productReservation.getId());
                if (type == 1) {
                    reSystemRecord.setRemarks("取消证书绑定");
                } else if (type == 2) {
                    reSystemRecord.setRemarks("取消资质绑定");
                }
                systemRecordService.save(reSystemRecord);
                productReservationDao.deleteByPrimaryKey(productReservation.getId());//删除掉
            }
        }
        Map map = new HashMap<String, Object>() {{
            put("scOrderId", scProductId);
        }};
        //查所有绑定的证书或者资质
        List<BaseCredential> baseCredentialList = baseCredentialDao.findCredentialListByScOrderId(map);
        Map<String, Object> storageMap = new HashMap<>();
        StorageCapacity storageCapacity;
        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacityList = new ArrayList<>();
        // 保存操作日志 基础证书表
        SystemRecord systemRecord = new SystemRecord();
        if (baseCredentialList != null && !baseCredentialList.isEmpty()) {
            for (BaseCredential baseCredential : baseCredentialList) {
                newStorageCapacityList.clear();//清空
                Map<String, Object> specialMap = new HashMap<>();
                specialMap.put("certificateId", baseCredential.getId());
                List<Map> storageList = certificateSpecialtyDao.findByCondition(specialMap);//根据证书ID查中间表
                String generalType = baseCredential.getGeneralType();//证书或资质
                boolean flag = false;
                //这里判断是资质或证书
                if (CredentialConstant.GENERAL_CREDENTIAL.equals(generalType) && type == 1) {
                    flag = true;
                } else if (CredentialConstant.ZZ_CREDENTIAL.equals(generalType) && type == 2) {//资质
                    flag = true;
                }
                if (flag) {
                    if (storageList != null && !storageList.isEmpty()) {
                        for (Map storage : storageList) {
                            String certificateCode = storage.get("certificateCode").toString();
                            storageMap.put("certificateCode", certificateCode);
                            storageCapacity = storageCapacityDao.findStorageCapacity(storageMap);//查出基础类型表,修改相关容量
                            // 预定量 - 1
                            storageCapacity.setReserveNumbers(storageCapacity.getReserveNumbers() - 1);
                            // 在库容量 +1
                            storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                            newStorageCapacityList.add(storageCapacity);
                        }
                    }
                    //清空基础表的 生产订单相关
                    if (CredentialConstant.GENERAL_CREDENTIAL.equals(generalType)) {//普通证书
                        baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE);//改为未使用
                        systemRecord.setRemarks("取消证书绑定");
                    } else if (CredentialConstant.ZZ_CREDENTIAL.equals(generalType)) {//资质
                        baseCredential.setCertificateStatus(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_ONE);//改为未使用
                        systemRecord.setRemarks("取消资质绑定");
                    }
                    baseCredential.setScOrderId(null);//取消绑定
                    baseCredential.setScOrderNo(null);
                    this.updateOpt(baseCredential, userEntity);//修改信息
                    systemRecord.setSource("2");//生产
                    systemRecord.setOperateType("2");// 操作类型  修改
                    systemRecord.setWorkTableName("zz_base_credential");
                    systemRecord.setWorkId(baseCredential.getId());
                    systemRecordService.save(systemRecord);
                    //修改库容量
                    storageCapacityService.updateStorageCapacityCount(newStorageCapacityList);//修改库容量
                    //查询是否有别的生产订单预约
                    BaseCredential newBaseCredential = generalCredentialService.boundProductReservation(baseCredential.getId(), newStorageCapacityList, false);
                    if (newBaseCredential == null) {//没有传出来才修改  不然在里面进行过修改了
                        baseCredentialDao.updateByPrimaryKey(baseCredential);//修改证书基础表
                    }
                }
            }
        }
    }

    /**
     * <p>@Description 办理中导出</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/31 0031 16:21 创建时间</p>
     * <p>@return</p>
     */
    public List<InprocessOrderVo> findExportProductOrder(Map params) {
        List<Map> srList = productOrderDao.queryInProcessListPage(params);
        List<InprocessOrderVo> voList = new LinkedList<>();
        for (Map map : srList) {
            InprocessOrderVo vo = new InprocessOrderVo();
            vo.setSignOrgName(String.valueOf(map.get("signOrgName") == null ? "" : map.get("signOrgName")));
            vo.setOrderNo(String.valueOf(map.get("orderNo") == null ? "" : map.get("orderNo")));
            vo.setScProductOrderNo(String.valueOf(map.get("scProductOrderNo") == null ? "" : map.get("scProductOrderNo")));
            vo.setCustomerName(String.valueOf(map.get("customerName") == null ? "" : map.get("customerName")));
            vo.setBusinessProductName(String.valueOf(map.get("businessProductName") == null ? "" : map.get("businessProductName")));
            vo.setProductName(String.valueOf(map.get("productName") == null ? "" : map.get("productName")));
            vo.setSignTime(String.valueOf(map.get("orderTime") == null ? "" : map.get("orderTime")));//签单时间
            vo.setSignUserName(String.valueOf(map.get("signUserName") == null ? "" : map.get("signUserName")));
            vo.setSignUserOrgName(String.valueOf(map.get("signUserOrgName") == null ? "" : map.get("signUserOrgName")));
            vo.setFlowUserName(String.valueOf(map.get("flowUserName") == null ? "" : map.get("flowUserName")));
            vo.setFlowUserOrgName(String.valueOf(map.get("flowUserOrgName") == null ? "" : map.get("flowUserOrgName")));
            vo.setOrderMoney(String.valueOf(map.get("money") == null ? "" : map.get("money")));//合同金额
            vo.setAssistUser(String.valueOf(map.get("assistUserName") == null ? "" : map.get("assistUserName")));//协单人员
            vo.setContractNo(String.valueOf(map.get("contractNo") == null ? "" : map.get("contractNo")));
            //最新备注时间和内容
            vo.setLastRemarkTime(String.valueOf(map.get("lastRemarkTime") == null ? "" : map.get("lastRemarkTime")));
            vo.setLastRemark(String.valueOf(map.get("lastRemark") == null ? "" : map.get("lastRemark")));
            vo.setCompanyName(String.valueOf(map.get("companyName") == null ? "" : map.get("companyName")));
            vo.setLatestEndNodeName(String.valueOf(map.get("latestEndNodeName") == null ? "" : map.get("latestEndNodeName")));
            if(StringUtils.isNotEmpty(map.get("noOrderOverdue"))){
                vo.setNoOrderOverdue(String.valueOf(Integer.valueOf(map.get("noOrderOverdue").toString()) >=0  ? map.get("noOrderOverdue"):""));
            }
            if(StringUtils.isNotEmpty(map.get("noContractOverdue"))){
                vo.setNoContractOverdue(String.valueOf(Integer.valueOf(map.get("noContractOverdue").toString()) >=0  ? map.get("noContractOverdue"):""));
            }
            if(null != map.get("contractStartDate")){
                vo.setContactDate(String.valueOf(map.get("contractStartDate"))+"-"+String.valueOf(map.get("contractEndDate")));
            }
            voList.add(vo);
        }
        return voList;
    }

    /**
     *获取更新节点操作信息
     * @param scProductOrder
     * @param map
     * @param scProductTimeStatus
     * @return
     */
    @Transactional
    public ProductNodeOperating saveProductNodeOperatingOld(ProductOrder scProductOrder, Map map, ProductTimeStatus scProductTimeStatus,UserEntity userEntity,ProductNode node) {
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到当前生产订单流程人员信息！");
        Map organizationEntity = commonMangerExtService.findOrg(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未获取到当前生产订单流程人员部门信息！");
        Integer  timeType= scProductTimeStatus.getNodeProcessTimeType() == null ? node.getIsNaturalorWorkday():Integer.valueOf(scProductTimeStatus.getNodeProcessTimeType());
        Integer  processTime= scProductTimeStatus.getNodeProcessTime() == null ? node.getHandleDate()/24 :scProductTimeStatus.getNodeProcessTime();
        ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
        scProductNodeOperating.setId(DggKeyWorker.nextId());
        scProductNodeOperating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
        scProductNodeOperating.setScProductOrderId(scProductOrder.getId());
        scProductNodeOperating.setScProductOrderNo(scProductOrder.getScProductOrderNo());
        scProductNodeOperating.setFlowOrgId(Long.valueOf(organizationEntity.get("id").toString()));
        scProductNodeOperating.setFlowOrgName(organizationEntity.get("name").toString());
        scProductNodeOperating.setFlowUserId(userEntity.getId());
        scProductNodeOperating.setFlowUserName(userEntity.getRealName().concat(userEntity.getLoginName()));
        scProductNodeOperating.setOrderStatus(scProductOrder.getStatus());
        scProductNodeOperating.setNodeId(scProductOrder.getLatestEndNodeId());
        scProductNodeOperating.setNodeName(scProductOrder.getLatestEndNodeName());
        scProductNodeOperating.setNodeProcessTimeType(timeType.toString()); //节点办理类型
        scProductNodeOperating.setNodeOpetateTime(new Date());
        //scProductNodeOperating.setIsExtract(node.getIsExtract());
        UserEntity currentUser = sessionManager.getCurrentUser();
        Map curOrg = commonMangerExtService.findOrg(currentUser.getOrgId());
        scProductNodeOperating.setCreaterOrgName(curOrg.get("name").toString());

        if (null != map.get("remark") && !"".equals(map.get("remark"))) {
            scProductNodeOperating.setRemark("更新节点:" + map.get("remark").toString());
        }
        scProductNodeOperating.setFlowType((String) map.get("flowType"));
        scProductNodeOperating.setStatus(Integer.valueOf((String) map.get("isPass")));
        //获取当前节点的配置的计算出的超期时间
        Date currentDate = null;
        if(null == scProductTimeStatus.getNodeEndTime()) {
            currentDate = commonService.getDateFromStartByType(scProductOrder.getLatestEndNodeTime(),
                    processTime, scProductTimeStatus.getNodeSuspendMillisecond() == null ? 0 : scProductTimeStatus.getNodeSuspendMillisecond(),
                    timeType);
        }else{
            currentDate=scProductTimeStatus.getNodeEndTime();
        }
        //判断当前节点是否超期
        if (currentDate.getTime() >= System.currentTimeMillis()) {
            scProductNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点超期状态
        } else {
            scProductNodeOperating.setNodeTimeStatus(ScProductConstant.TIME_OUT); //节点超期状态
            String date = DateUtils.transTime(currentDate, new Date());
            scProductNodeOperating.setNodeOverdueTime(date); //节点超期时间
        }
        scProductNodeOperating.setNodeProcessTime(scProductTimeStatus.getNodeProcessTime());
        scProductNodeOperating.setNodeStartTime(scProductTimeStatus.getNodeStartTime());
        scProductNodeOperating.setNodeEndTime(scProductTimeStatus.getNodeEndTime());
        return scProductNodeOperating;
    }
    public ProductNodeOperating saveProductNodeOperating(ProductOrder scProductOrder, Map map, ProductTimeStatus scProductTimeStatus,UserEntity userEntity,Node node) {
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到当前生产订单流程人员信息！");
        Map organizationEntity = commonMangerExtService.findOrg(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未获取到当前生产订单流程人员部门信息！");
        Integer  timeType= scProductTimeStatus.getNodeProcessTimeType() == null ? node.getIsNaturalorWorkday():Integer.valueOf(scProductTimeStatus.getNodeProcessTimeType());
        Integer  processTime= scProductTimeStatus.getNodeProcessTime() == null ? node.getHandleDate()/24 :scProductTimeStatus.getNodeProcessTime();
        ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
        scProductNodeOperating.setId(DggKeyWorker.nextId());
        scProductNodeOperating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
        scProductNodeOperating.setScProductOrderId(scProductOrder.getId());
        scProductNodeOperating.setScProductOrderNo(scProductOrder.getScProductOrderNo());
        scProductNodeOperating.setFlowOrgId(Long.valueOf(organizationEntity.get("id").toString()));
        scProductNodeOperating.setFlowOrgName(organizationEntity.get("name").toString());
        scProductNodeOperating.setFlowUserId(userEntity.getId());
        scProductNodeOperating.setFlowUserName(userEntity.getRealName().concat(userEntity.getLoginName()));
        scProductNodeOperating.setOrderStatus(scProductOrder.getStatus());
        scProductNodeOperating.setNodeId(scProductOrder.getLatestEndNodeId());
        scProductNodeOperating.setNodeName(scProductOrder.getLatestEndNodeName());
        scProductNodeOperating.setNodeProcessTimeType(timeType.toString()); //节点办理类型
        scProductNodeOperating.setNodeOpetateTime(new Date());
        scProductNodeOperating.setIsExtract(node.getIsExtract());
        UserEntity currentUser = sessionManager.getCurrentUser();
        Map curOrg = commonMangerExtService.findOrg(currentUser.getOrgId());
        scProductNodeOperating.setCreaterOrgName(curOrg.get("name").toString());

        if (null != map.get("remark") && !"".equals(map.get("remark"))) {
            scProductNodeOperating.setRemark("更新节点:" + map.get("remark").toString());
        }
        scProductNodeOperating.setFlowType((String) map.get("flowType"));
        scProductNodeOperating.setStatus(Integer.valueOf((String) map.get("isPass")));
        //获取当前节点的配置的计算出的超期时间
        Date currentDate = null;
        if(null == scProductTimeStatus.getNodeEndTime()) {
            currentDate = commonService.getDateFromStartByType(scProductOrder.getLatestEndNodeTime(),
                    processTime, scProductTimeStatus.getNodeSuspendMillisecond() == null ? 0 : scProductTimeStatus.getNodeSuspendMillisecond(),
                    timeType);
        }else{
            currentDate=scProductTimeStatus.getNodeEndTime();
        }
        //判断当前节点是否超期
        if (currentDate.getTime() >= System.currentTimeMillis()) {
            scProductNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点超期状态
        } else {
            scProductNodeOperating.setNodeTimeStatus(ScProductConstant.TIME_OUT); //节点超期状态
            String date = DateUtils.transTime(currentDate, new Date());
            scProductNodeOperating.setNodeOverdueTime(date); //节点超期时间
        }
        scProductNodeOperating.setNodeProcessTime(scProductTimeStatus.getNodeProcessTime());
        scProductNodeOperating.setNodeStartTime(scProductTimeStatus.getNodeStartTime());
        scProductNodeOperating.setNodeEndTime(scProductTimeStatus.getNodeEndTime());
        return scProductNodeOperating;
    }

    /**
     *
     * @param node
     * @param order
     * @return
     */
    @Transactional
    public ProductTimeStatus saveProductTimeStatus(Node node,ProductOrder order){
        ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(order.getId());
        //写入下一个节点信息
        Integer hours = 0;
        if(null != node) {
            timestatus.setNodeId(node.getId().toString());
            timestatus.setNodeName(node.getName());
            hours = node.getHandleDate();
            timestatus.setNodeProcessTimeType(node.getIsNaturalorWorkday());

            long currentTime = System.currentTimeMillis();
            Date date = new Date(currentTime);
            timestatus.setNodeStartTime(date);
            long milliSecond = 0;
            if (hours > 0) {
                milliSecond= hours * 3600 * 1000;
            }
            //获取当前节点的配置的计算出的超期时间
            /*Date currentDate = commonService.getDateFromStartByType(date,
                    (int) Math.ceil((double)node.getHandleDate()/24), milliSecond,
                    node.getIsNaturalorWorkday());*/
            Integer nodeProcessTimeType = node.getIsNaturalorWorkday();
            if (nodeProcessTimeType == 1){//工作日
                timestatus.setNodeEndTime(commonService.getWorkDateFromHour(date,hours+24));
            }
            if (nodeProcessTimeType == 2){//自然日
                timestatus.setNodeEndTime(commonService.getDateFromHour(date,hours+24));
            }
            timestatus.setNodeEndTime(DateUtils.getDate(DateUtils.dateString(timestatus.getNodeEndTime(),"yyyy-MM-dd"),"yyyy-MM-dd"));
            timestatus.setNodeProcessTime(hours / 24);
            timestatus.setNodeSuspendMillisecond(milliSecond);
            timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);
        }
        return timestatus;
    }
    @Transactional
    public ProductTimeStatus saveProductTimeStatusOld(ProductNode node,ProductOrder order){
        ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(order.getId());
        //写入下一个节点信息
        Integer hours = 0;
        if(null != node) {
            timestatus.setNodeId(node.getId().toString());
            timestatus.setNodeName(node.getName());
            hours = node.getHandleDate()*24;
            timestatus.setNodeProcessTimeType(node.getIsNaturalorWorkday());

            long currentTime = System.currentTimeMillis();
            Date date = new Date(currentTime);
            timestatus.setNodeStartTime(date);
            long milliSecond = 0;
            if (hours > 0) {
                milliSecond= hours * 3600 * 1000;
            }
            //获取当前节点的配置的计算出的超期时间
            Date currentDate = commonService.getDateFromStartByType(date,
                    node.getHandleDate()/24, milliSecond,
                    node.getIsNaturalorWorkday());
            timestatus.setNodeEndTime(DateUtils.getDate(DateUtils.dateString(currentDate,"yyyy-MM-dd"),"yyyy-MM-dd"));
            timestatus.setNodeProcessTime(hours / 24);
            timestatus.setNodeSuspendMillisecond(milliSecond);
            timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);
        }
        return timestatus;
    }

    /**
     * <p>@Description 保存更新节点信息</p>
     * <p>@author mqy</p>
     * <p>@Time 2019-05-13 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public Integer saveNodeUpdateNew(ProductOrder scProductOrder, Map map, UserEntity userEntity, ProductTimeStatus scProductTimeStatus,ProductNodeOperating scProductNodeOperating) throws Exception {
        List<ProductData> productDataList = productDataDao.query(new HashMap<String, Object>() {{
            put("scProductId", scProductOrder.getId());
        }});
        int returnType = 0;
        if (productDataList != null && !productDataList.isEmpty()) {
            ProductData productData = productDataList.get(0);
            productData.setScProductId(scProductOrder.getId());
            productData.setScProductNo(scProductOrder.getScProductOrderNo());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //渠道
            if (null != map.get("channelName") && !"".equals(map.get("channelName"))) {
                productData.setChannelName(map.get("channelName").toString());
            }
            //资料交接数
            if (null != map.get("dataTransferNum") && !"".equals(map.get("dataTransferNum"))) {
                productData.setDataTransferNum(map.get("dataTransferNum").toString());
            }
            //网上审批时间
            if (null != map.get("netApprovalTime") && !"".equals(map.get("netApprovalTime"))) {
                productData.setNetApprovalTime(sdf.parse(map.get("netApprovalTime").toString()));
            }
            //评审时间
            if (null != map.get("reviewTime") && !"".equals(map.get("reviewTime"))) {
                productData.setReviewTime(sdf.parse(map.get("reviewTime").toString()));
            }
            //评审结果
            if (null != map.get("reviewResult") && !"".equals(map.get("reviewResult"))) {
                productData.setReviewResult(map.get("reviewResult").toString());
            }
            //公示时间
            if (null != map.get("publicityTime") && !"".equals(map.get("publicityTime"))) {
                productData.setPublicityTime(sdf.parse(map.get("publicityTime").toString()));
            }
            //报名时间
            if (null != map.get("signupTime") && !"".equals(map.get("signupTime"))) {
                productData.setSignupTime(sdf.parse(map.get("signupTime").toString()));
            }
            //换证时间
            if (null != map.get("replacementTime") && !"".equals(map.get("replacementTime"))) {
                productData.setReplacementTime(sdf.parse(map.get("replacementTime").toString()));
            }
            //打证时间
            if (null != map.get("playingcardsTime") && !"".equals(map.get("playingcardsTime"))) {
                productData.setPlayingcardsTime(sdf.parse(map.get("playingcardsTime").toString()));
            }
            //领证时间
            if (null != map.get("licensingTime") && !"".equals(map.get("licensingTime"))) {
                productData.setLicensingTime(sdf.parse(map.get("licensingTime").toString()));
            }
            //渠道返点
            if (null != map.get("channelRebates") && !"".equals(map.get("channelRebates"))) {
                productData.setChannelRebates(new BigDecimal(map.get("channelRebates").toString()));
            }
            //对外返点
            if (null != map.get("foreignRebates") && !"".equals(map.get("foreignRebates"))) {
                productData.setForeignRebates(new BigDecimal(map.get("foreignRebates").toString()));
            }
            //公示号
            if (null != map.get("publicityNum") && !"".equals(map.get("publicityNum"))) {
                productData.setPublicityNum(map.get("publicityNum").toString());
            }
            //公告时间
            if (null != map.get("noticeTime") && !"".equals(map.get("noticeTime"))) {
                productData.setNoticeTime(sdf.parse(map.get("noticeTime").toString()));
            }
            //公告号
            if (null != map.get("noticeNum") && !"".equals(map.get("noticeNum"))) {
                productData.setNoticeNum(map.get("noticeNum").toString());
            }
            //公告时间
            if (null != map.get("channelHisTime") && !"".equals(map.get("channelHisTime"))) {
                productData.setChannelHisTime(sdf.parse(map.get("channelHisTime").toString()));
            }
            //资质公司
            if (null != map.get("company") && !"".equals(map.get("company"))) {
                productData.setCompany(map.get("company").toString());
            }
            //招标文件
            if (null != map.get("biddingDocuments") && !"".equals(map.get("biddingDocuments"))) {
                productData.setBiddingDocuments(map.get("biddingDocuments").toString());
            }
            //招标清单
            if (null != map.get("biddingList") && !"".equals(map.get("biddingList"))) {
                productData.setBiddingList(map.get("biddingList").toString());
            }
            //标书数量
            if (null != map.get("bidingNum") && !"".equals(map.get("bidingNum"))) {
                productData.setBidingNum(map.get("bidingNum").toString());
            }
            //交标书时间
            if (null != map.get("handoveBidingTime") && !"".equals(map.get("handoveBidingTime"))) {
                productData.setHandoveBidingTime(sdf.parse(map.get("handoveBidingTime").toString()));
            }
            //公示文件
            if (null != map.get("publicityFile") && !"".equals(map.get("publicityFile"))) {
                productData.setPublicityFile(map.get("publicityFile").toString());
            }
            //审批通告时间
            if (null != map.get("approvalNoticeTime") && !"".equals(map.get("approvalNoticeTime"))) {
                productData.setApprovalNoticeTime(sdf.parse(map.get("approvalNoticeTime").toString()));
            }
            if (StringUtils.isNotEmpty(map.get("remark"))) {
                scProductOrder.setRemark(map.get("remark").toString());
                scProductOrder.setLastRemark(map.get("remark").toString());
                scProductOrder.setLastRemarkTime(new Date());
                scProductOrder.setLastUser(userEntity.getRealName().concat(userEntity.getLoginName()));
            }

            //判断完结类型
            if(null !=scProductNodeOperating.getNodeName()) {
                if (null != scProductOrder.getContractEndDate()) {
                    Date contractEndeDate = DateUtils.getDate(DateUtils.dateString(scProductOrder.getContractEndDate(), "yyyy-MM-dd") + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
                    Date orderEndDate = scProductTimeStatus.getOrderEndTime();
                    if (scProductNodeOperating.getNodeName().equals("完结") && (contractEndeDate.getTime() < new Date().getTime() || orderEndDate.getTime() < new Date().getTime())) {
                        scProductOrder.setStatus(ScProductConstant.SC_ORDER_OVER_OVERDUE);
                    }
                } else {
                    Date orderEndDate = scProductTimeStatus.getOrderEndTime();
                    if (scProductNodeOperating.getNodeName().equals("完结") && orderEndDate.getTime() < new Date().getTime()) {
                        scProductOrder.setStatus(ScProductConstant.SC_ORDER_OVER_OVERDUE);
                    }
                }
            }
            //保存操作记录
            SystemRecord systemRecord = new SystemRecord();
            systemRecord.setWorkId(productData.getId());
            systemRecord.setWorkTableName("zzsc_product_data");
            systemRecord.setRemarks("修改业态信息");
            systemRecord.setOperateType("2");//修改
            systemRecord.setSource("2");//来源生产
            systemRecordService.save(systemRecord);
            //-----------------保存更新节点记录      --------------------
//            //写入流程人员
//            saveScProductFlowUser(map.get("flowUserId").toString(),scProductOrder,userEntity);
            //修改生产订单子表
            this.updateOpt(scProductOrder, userEntity);
            productOrderDao.updateByPrimaryKey(scProductOrder);
            //保存业态独有字段数据
            productDataDao.updateByPrimaryKey(productData);
            if(null !=scProductNodeOperating.getScProductOrderId()) {
                //保存更新节点数据
                this.saveOpt(scProductNodeOperating, userEntity);
                productNodeOperatingDao.insert(scProductNodeOperating);
            }
            //更新超期表
            this.updateOpt(scProductTimeStatus, userEntity);
            productTimeStatusDao.updateByPrimaryKey(scProductTimeStatus);
            return returnType;
        }
        return returnType;
    }

    /**
     * 完结节点更新验证
     * @param order
     * @param nodeName
     * @return 证书匹配表示有证书匹配，关键节点表示关键节点未更完
     */
    public String verifyFinish(ProductOrder order,String nodeName){
        if("强制完结".equals(nodeName) || "完结".equals(nodeName)) {
            Map param = new HashMap();
            param.put("scOrderId", order.getId());
            List<BaseCredential> list = baseCredentialDao.findCredentialListByScOrderId(param);
            if (list.size() > 0) {
                for (BaseCredential baseCredential : list) {
                    if (CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH.equals(baseCredential.getCertificateStatus())) {
                        return "该订单有证书匹配无法完结！";
                    }
                }
            }
        }
        return null;
    }

    /**
     * 强制完结顶单
     * @param params
     * @param userEntity
     */
    @Transactional
    public void forceOverOrder(Map params, UserEntity userEntity) {
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ProductOrder scProductOrder = this.productOrderDao.selectByPrimaryKey(Long.parseLong(params.get("scorderId").toString()));
        ValidateUtils.strNotEmpty(scProductOrder, ProductOrderExcption.class, "未获取到生产订单的信息！");
        //跟新订单表为完结
        String msg = verifyFinish(scProductOrder,"强制完结");
        ValidateUtils.isTrue(null == msg, ProductOrderExcption.class, msg);
        List<ProductTimeStatus> productTimeStatusList = productTimeStatusDao.query(new HashMap<String, Object>() {{
            put("id", scProductOrder.getId());
        }});
        ProductTimeStatus scProductTimeStatus = new ProductTimeStatus();

        scProductOrder.setStatus(ScProductConstant.SC_ORDER_OVER_FORCE);
        scProductOrder.setCompletedTime(new Date());
        params.put("isPass","1");
        scProductOrder.setFlowUserId(userEntity.getId());
        scProductOrder.setFlowUserName(userEntity.getRealName().concat(userEntity.getLoginName()));
        Map org = commonMangerExtService.findOrg(userEntity.getOrgId());
        if (null != org) {
            scProductOrder.setFlowUserOrgId(Long.parseLong(org.get("id").toString()));
            scProductOrder.setFlowUserOrgName(org.get("name").toString());
        }
        scProductOrder.setRemark(params.get("remark").toString());
        scProductOrder.setLastRemark(params.get("remark").toString());
        scProductOrder.setLastRemarkTime(new Date());
        scProductOrder.setLastUser(userEntity.getRealName().concat(userEntity.getLoginName()));
        //修改生产订单子表
        this.updateOpt(scProductOrder, userEntity);
        productOrderDao.updateByPrimaryKey(scProductOrder);
        //更新超期表
        this.updateOpt(scProductTimeStatus, userEntity);
        productTimeStatusDao.updateByPrimaryKey(scProductTimeStatus);
        //操作记录
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setWorkNo(scProductOrder.getScProductOrderNo());
        systemRecord.setWorkId(scProductOrder.getId());
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setSource("2");//来源生产
        systemRecord.setOperateType("37");//操作类型 : 强制完结
        systemRecord.setRemarks("强制完结订单");
        systemRecordService.save(systemRecord);
        try {// 发送消息 生产订单{0}已经于{1}分配给你，请及时确认处理！
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(scProductOrder.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(scProductOrder.getId());
            customerRecord.setTableNo(scProductOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE11);
            customerRecord.setCreaterId(userEntity.getId());
            if (StringUtils.isNotEmpty(params.get("remark"))){
                customerRecord.setContent(params.get("remark").toString());
            }
            MQMessageSendUtil.ucMessageSend(customerRecord);

            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(scProductOrder, null,  userEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String msgConent="您好，您的客户"+scProductOrder.getCustomerName()+"订单"+scProductOrder.getOrderNo()+"办理的"
                +scProductOrder.getScProductOrderNo()+"业务，订单已强制完结，请及时确认处理";
        commonService.sendQgjMessage(scProductOrder.getOrderId(),scProductOrder.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
    }

    /**
     *超期扣罚
     * @param order
     * @param node
     * @param productTimeStatus
     * @return
     */
    public Integer nodeTimeOutPunish(ProductOrder order,Node node,ProductTimeStatus productTimeStatus){
        Map flowUser = commonMangerExtService.searchUserById(order.getFlowUserId());
        List<TimeoutPunishDto> list = new ArrayList<>();
        TimeoutPunishDto timeoutPunishDto = new TimeoutPunishDto();
        timeoutPunishDto.setBusinessCode(order.getBusinessTypeCode());
        timeoutPunishDto.setBusinessName(order.getBusinessTypeName());
        timeoutPunishDto.setFlowUserId(order.getFlowUserId());
        timeoutPunishDto.setFlowUserName(order.getFlowUserName());
        timeoutPunishDto.setProductOrgId(order.getProductOrgId());
        timeoutPunishDto.setProductOrgName(order.getProductOrgName());
        timeoutPunishDto.setOrgId(order.getFlowUserOrgId());
        timeoutPunishDto.setOrgName(order.getFlowUserOrgName());
        timeoutPunishDto.setOrderId(order.getOrderId());
        timeoutPunishDto.setOrderNo(order.getOrderNo());
        timeoutPunishDto.setProductOrderId(order.getId());
        timeoutPunishDto.setProductOrderNo(order.getScProductOrderNo());
        timeoutPunishDto.setCustomerId(order.getCustomerId());
        timeoutPunishDto.setCustomerName(order.getCustomerName());
        timeoutPunishDto.setCustomerNo(order.getCustomerNo());
        timeoutPunishDto.setCustomerPhone(order.getCustomerPhone());
        timeoutPunishDto.setNoId(node.getId());
        timeoutPunishDto.setNoCode(node.getCode());
        timeoutPunishDto.setNoName(node.getName());
        timeoutPunishDto.setVersion(node.getVersion());
        timeoutPunishDto.setTimeOutTime(productTimeStatus.getNodeEndTime());
        timeoutPunishDto.setPunishTime(new Date());
        list.add(timeoutPunishDto);
        Map param = new HashMap(1);
        param.put("timeoutPunishListDtos",list);
        return nodeTimeOutPunishService.nodeTimeOutPunish(param);
    }

    /**
     * 判断是否进行节点超期扣罚
     * @param order
     * @param productTimeStatus
     * @return
     */
    private boolean isNodeTimeOutPunish(ProductOrder order,ProductTimeStatus productTimeStatus) {
        Node node = flowService.queyNodeListById(order.getCurrentNodeId(),order.getId());
        if(null==productTimeStatus.getNodeEndTime()){
            return false;
        }
        if(null == node.getIsPunish()){
            return false;
        }
        if(node.getIsPunish()==1 &&  productTimeStatus.getNodeEndTime().getTime() < new Date().getTime() && (null == order.getPunishStatus() || 0 == order.getPunishStatus())){
            return true;
        }
        return false;
    }

    //证书匹配扣罚
    public Map isMatchingPunish(ProductOrder order,BaseCredential baseCredential){
        Map returnMap = new HashMap();
        CredentialInfo credentialInfo = credentialInfoService.getCredentialInfoById(baseCredential.getId());
        CertificateMatchingEntity certificateMatchingEntity =certificateMatchingService.getMatchingByMap(credentialInfo.getCertificateSpecialtyId(),credentialInfo.getCertificateTypeId(),credentialInfo.getCertificateLevel());
        if(null == certificateMatchingEntity){
            return returnMap;
        }
        if( 1 == order.getPunishStatus()){
            return returnMap;
        }
        if(null == credentialInfo.getCertificateUserOrgId() || null == credentialInfo.getCertificateUserOrgName()){
            return returnMap;
        }

        Integer days = certificateMatchingEntity.getMatchingTime();
        Integer isNatureOrWorkDay = certificateMatchingEntity.getIsNatureWorkDay();
        Date currentDate = commonService.getDateFromStartByType(credentialInfo.getLastOutgoingTime(),
                days,Long.valueOf(days)*24*3600*1000,
                isNatureOrWorkDay);
        if (currentDate.getTime() <= System.currentTimeMillis()) {
            returnMap.put("timeOutTime",currentDate);
            returnMap.put("certificateUserId",credentialInfo.getCertificateUserId());
            returnMap.put("certificateUserName",credentialInfo.getCertificateUserName());
            returnMap.put("certificateUserOrgId",credentialInfo.getCertificateUserOrgId());
            returnMap.put("certificateUserOrgName",credentialInfo.getCertificateUserOrgName());
            if(certificateMatchingEntity.getUnit()==1){
                returnMap.put("money",certificateMatchingEntity.getPunishCount());
            }else{
                returnMap.put("points",certificateMatchingEntity.getPunishCount());
            }
            return returnMap;
        }else{
            return returnMap;
        }
    }
    public Integer matchingPunish(Map params,ProductOrder order){
        UserEntity userEntity = sessionManager.getCurrentUser();
        List<TimeoutPunishDto> list = new ArrayList<>();
        TimeoutPunishDto timeoutPunishDto = new TimeoutPunishDto();
        timeoutPunishDto.setBusinessCode(order.getBusinessTypeCode());
        timeoutPunishDto.setBusinessName(order.getBusinessTypeName());
        timeoutPunishDto.setFlowUserId(Long.valueOf(params.get("certificateUserId").toString()));
        timeoutPunishDto.setFlowUserName(params.get("certificateUserName").toString());
        timeoutPunishDto.setProductOrgId(order.getProductOrgId());
        timeoutPunishDto.setProductOrgName(order.getProductOrgName());
        timeoutPunishDto.setOrgId(Long.valueOf(params.get("certificateUserOrgId").toString()));
        timeoutPunishDto.setOrgName(params.get("certificateUserOrgName").toString());
        timeoutPunishDto.setOrderId(order.getOrderId());
        timeoutPunishDto.setOrderNo(order.getOrderNo());
        timeoutPunishDto.setProductOrderId(order.getId());
        timeoutPunishDto.setProductOrderNo(order.getScProductOrderNo());
        timeoutPunishDto.setNoCode("zspp");
        timeoutPunishDto.setNoName("证书匹配");
        timeoutPunishDto.setVersion("version1");
        timeoutPunishDto.setTimeOutTime((Date) params.get("timeOutTime"));
        timeoutPunishDto.setPunishTime(new Date());
        timeoutPunishDto.setUpdaterId(userEntity.getId());
        timeoutPunishDto.setUpdaterName(userEntity.getRealName().concat(userEntity.getLoginName()));
        timeoutPunishDto.setCustomerId(order.getCustomerId());
        timeoutPunishDto.setCustomerName(order.getCustomerName());
        timeoutPunishDto.setCustomerNo(order.getCustomerNo());
        timeoutPunishDto.setCustomerPhone(order.getCustomerPhone());
        timeoutPunishDto.setType(2);
        Map org = commonMangerExtService.findOrg(userEntity.getOrgId());
        if (null != org) {
            timeoutPunishDto.setUpdaterOrgId(Long.parseLong(org.get("id").toString()));
            timeoutPunishDto.setUpdaterOrgName(org.get("name").toString());
        }
        timeoutPunishDto.setUpdateTime(new Date());
        if(params.containsKey("points")){
            timeoutPunishDto.setPoints(new BigDecimal(params.get("points").toString()));
            timeoutPunishDto.setMoney(new BigDecimal(0));
        }
        if(params.containsKey("money")){
            timeoutPunishDto.setMoney(new BigDecimal(params.get("money").toString()));
            timeoutPunishDto.setPoints(new BigDecimal(0));
        }
        timeoutPunishDto.setCreateTime(new Date());
        list.add(timeoutPunishDto);
        Map param = new HashMap(1);
        param.put("timeoutPunishListDtos",list);
        return nodeTimeOutPunishService.matchingtPunish(param);

    }

    /**
     * 获取企管家用户
     * @param orderId
     * @return
     */
    public String getQgjUser(Long orderId,String businessTypeId){
        String qgjUser="";
        // 通过调取企管家的接口查询
        Map parm = new HashMap();
        parm.put("id",orderId);
        parm.put("businessTypeId",businessTypeId);
        String resuObj = null;
        try {
            resuObj = HttpUtility.getRest(initComponent.getQgjUserUrl()+ ApiUrlConstant.QGJ_USER,parm);
        } catch (IOException e) {
            throw new CommonExcption("企管家后台报错");
        }
        ResultObj result = JsonUtil.json2Obj(resuObj, ResultObj.class);
        Map qgjMap = JsonUtil.json2Obj(result.getData(), Map.class);
        if (null != qgjMap) {
            //判断返回订单中是否有人员名字和工号
            if (StringUtils.isNotEmpty(qgjMap.get("serviceStaffName"))) {
                qgjUser = null == qgjMap.get("serviceStaffName") ? null : qgjMap.get("serviceStaffName").toString();
            }
        }
        return qgjUser;
    }

    /**
     * 获取企管家用户ID
     * @param orderId
     * @return
     */
    public Long getQgjUserId(Long orderId,String businessTypeId){
        Long qgjUserId = null;
        // 通过调取企管家的接口查询
        Map parm = new HashMap();
        parm.put("id",orderId);
        parm.put("businessTypeId",businessTypeId);
        String resuObj = null;
        try {
            resuObj = HttpUtility.getRest(initComponent.getQgjUserUrl()+ ApiUrlConstant.QGJ_USER,parm);
        } catch (IOException e) {
            throw new CommonExcption("企管家后台报错");
        }
        if(StringUtils.isNotEmpty(resuObj)){
            ResultObj result = JsonUtil.json2Obj(resuObj, ResultObj.class);
            Map qgjMap = JsonUtil.json2Obj(result.getData(), Map.class);
            if (null != qgjMap) {
                //判断返回订单中是否有人员名字和工号
                if (StringUtils.isNotEmpty(qgjMap.get("serviceStaffId"))) {
                    qgjUserId = null == qgjMap.get("serviceStaffId") ? null : Long.parseLong(qgjMap.get("serviceStaffId").toString());
                }
            }
        }
        return qgjUserId;
    }

    public List getQgjListREemark(Map parm) {
        String resuObj = null;
        try {
            resuObj = HttpUtility.postRest(initComponent.getQgjUserUrl() + ApiUrlConstant.QGJ_LIST_REMARK, parm);
        } catch (IOException e) {
            throw new CommonExcption("企管家后台报错");
        }

        ResultObj result = JsonUtil.json2Obj(resuObj, ResultObj.class);
//        List<QgjResultBo> list = JsonUtil.json2Obj(result.getData(), List.class);
        String s = result.getData();
        ResultVo resultVo = JSON.parseObject(s, ResultVo.class);
        parm.put("count",resultVo.getTotal());
        return resultVo.getData();
    }
}
